Made Counter less complex
This commit is contained in:
parent
dbe47ce235
commit
6d0f45d0f4
55
counter.go
55
counter.go
|
@ -1,6 +1,8 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import ()
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
MaxIndex = ^uint(0)
|
MaxIndex = ^uint(0)
|
||||||
|
@ -8,44 +10,57 @@ const (
|
||||||
|
|
||||||
type (
|
type (
|
||||||
Counter struct {
|
Counter struct {
|
||||||
Write uint
|
WriteIndex uint
|
||||||
Read uint
|
ReadIndex uint
|
||||||
|
mutex sync.Mutex
|
||||||
stream chan uint
|
stream chan uint
|
||||||
inLoop bool
|
streaming bool
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewCounter(wi, ri uint) *Counter {
|
func NewCounter(wi, ri uint) Counter {
|
||||||
c := &Counter{Write: wi, Read: ri}
|
c := Counter{
|
||||||
c.stream = make(chan uint)
|
WriteIndex: wi,
|
||||||
go c.Loop()
|
ReadIndex: ri,
|
||||||
|
stream: make(chan uint),
|
||||||
|
streaming: false,
|
||||||
|
}
|
||||||
|
if c.Distance() > 0 {
|
||||||
|
go c.Stream()
|
||||||
|
}
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Counter) Incr() {
|
func (c *Counter) Write(proc func(i uint) bool) {
|
||||||
c.Write++
|
c.mutex.Lock()
|
||||||
if !c.inLoop {
|
defer c.mutex.Unlock()
|
||||||
c.inLoop = true
|
|
||||||
go c.Loop()
|
ok := proc(c.WriteIndex + 1)
|
||||||
|
if ok {
|
||||||
|
c.WriteIndex++
|
||||||
|
if !c.streaming {
|
||||||
|
go c.Stream()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Counter) Next() uint {
|
func (c *Counter) Read() uint {
|
||||||
return <-c.stream
|
return <-c.stream
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Counter) Distance() uint {
|
func (c *Counter) Distance() uint {
|
||||||
d := c.Write - c.Read
|
d := c.WriteIndex - c.ReadIndex
|
||||||
if d < 0 {
|
if d < 0 {
|
||||||
d += MaxIndex
|
d += MaxIndex
|
||||||
}
|
}
|
||||||
return d
|
return d
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Counter) Loop() {
|
func (c *Counter) Stream() {
|
||||||
for c.Write > c.Read {
|
c.streaming = true
|
||||||
c.stream <- c.Read + 1
|
for c.WriteIndex > c.ReadIndex {
|
||||||
c.Read++
|
c.stream <- c.ReadIndex + 1
|
||||||
|
c.ReadIndex++
|
||||||
}
|
}
|
||||||
c.inLoop = false
|
c.streaming = false
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue