float64.go raw
1 package ring
2
3 type BufferFloat64 struct {
4 Buf []float64
5 Cursor int
6 Full bool
7 }
8
9 func NewBufferFloat64(size int) *BufferFloat64 {
10 return &BufferFloat64{
11 Buf: make([]float64, size),
12 Cursor: -1,
13 }
14 }
15
16 // Get returns the value at the given index or nil if nothing
17 func (b *BufferFloat64) Get(index int) (out *float64) {
18 bl := len(b.Buf)
19 if index < bl {
20 cursor := b.Cursor + index
21 if cursor > bl {
22 cursor = cursor - bl
23 }
24 return &b.Buf[cursor]
25 }
26 return
27 }
28 func (b *BufferFloat64) Len() (length int) {
29 if b.Full {
30 return len(b.Buf)
31 }
32 return b.Cursor
33 }
34
35 func (b *BufferFloat64) Add(value float64) {
36 b.Cursor++
37 if b.Cursor == len(b.Buf) {
38 b.Cursor = 0
39 if !b.Full {
40 b.Full = true
41 }
42 }
43 b.Buf[b.Cursor] = value
44 }
45
46 func (b *BufferFloat64) ForEach(fn func(v float64) error) (err error) {
47 c := b.Cursor
48 i := c + 1
49 if i == len(b.Buf) {
50 // log.L.Debug("hit the end")
51 i = 0
52 }
53 if !b.Full {
54 // log.L.Debug("buffer not yet full")
55 i = 0
56 }
57 // log.L.Debug(b.Buf)
58 for ; ; i++ {
59 if i == len(b.Buf) {
60 // log.L.Debug("passed the end")
61 i = 0
62 }
63 if i == c {
64 // log.L.Debug("reached cursor again")
65 break
66 }
67 // log.L.Debug(i, b.Cursor)
68 if err = fn(b.Buf[i]); err != nil {
69 break
70 }
71 }
72 return
73 }
74