Created
April 2, 2016 03:18
-
-
Save marconi/ff8610383985411ba8f02996501b3999 to your computer and use it in GitHub Desktop.
Ring buffer example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type RingBuffer struct { | |
size int | |
buffer []int | |
head int | |
tail int | |
} | |
func NewRingBuffer(size int) *RingBuffer { | |
buffer := make([]int, size) | |
for i, _ := range buffer { | |
buffer[i] = -1 | |
} | |
return &RingBuffer{ | |
size: size, | |
buffer: buffer, | |
head: 0, | |
tail: 0, | |
} | |
} | |
func (buffer *RingBuffer) Push(i int) error { | |
// if current tail is free, use it | |
if buffer.buffer[buffer.tail] == -1 { | |
buffer.buffer[buffer.tail] = i | |
return nil | |
} | |
// if not, move to next slot | |
newTail := buffer.tail + 1 | |
// if next slot is last slot, reset to zero | |
if buffer.tail == buffer.size-1 { | |
newTail = 0 | |
} | |
// if new tail is empty, use it | |
if buffer.buffer[newTail] == -1 { | |
buffer.buffer[newTail] = i | |
buffer.tail = newTail | |
return nil | |
} | |
return fmt.Errorf("Queue is full") | |
} | |
func (buffer *RingBuffer) Pop() (int, error) { | |
if buffer.buffer[buffer.head] != -1 { | |
i := buffer.buffer[buffer.head] | |
buffer.buffer[buffer.head] = -1 | |
if buffer.head+1 < buffer.size { | |
buffer.head++ | |
} else { | |
buffer.head = 0 | |
} | |
return i, nil | |
} | |
return -1, fmt.Errorf("Head is empty") | |
} | |
func main() { | |
size := 10 | |
buffer := NewRingBuffer(size) | |
buffer.Push(1) | |
buffer.Push(2) | |
buffer.Push(3) | |
buffer.Push(4) | |
buffer.Push(5) | |
buffer.Pop() | |
buffer.Pop() | |
buffer.Pop() | |
buffer.Push(6) | |
buffer.Push(7) | |
buffer.Push(8) | |
buffer.Pop() | |
fmt.Printf("%#v\n", buffer.buffer) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment