Skip to content

Instantly share code, notes, and snippets.

@dizcza
Last active July 13, 2019 21:29
Show Gist options
  • Save dizcza/21b7636018a24edc63fc21e7592e3478 to your computer and use it in GitHub Desktop.
Save dizcza/21b7636018a24edc63fc21e7592e3478 to your computer and use it in GitHub Desktop.
Ring buffer to hold the UART data
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Ring buffer (fixed size queue) implementation using a circular array (array
* with wrap-around).
*/
public class RingByteBuffer implements Iterable<Byte> {
private final byte[] buffer; // queue elements
private int indexTail = 0; // index of first element of queue
private int indexHead = 1; // index of next available slot
public RingByteBuffer(int capacity) {
buffer = new byte[capacity + 1];
}
public boolean isEmpty() {
return size() == 0;
}
public int size() {
return (indexHead - indexTail - 1) % buffer.length;
}
public void put(byte item) {
if (indexHead == indexTail) {
indexTail = (indexTail + 1) % buffer.length;
}
buffer[indexHead] = item;
indexHead = (indexHead + 1) % buffer.length;
}
public void put(byte[] items) {
for (byte item : items) {
put(item);
}
}
public byte get() {
if (isEmpty()) {
throw new RuntimeException("Ring buffer underflow");
}
byte item = buffer[indexTail];
indexTail = (indexTail + 1) % buffer.length;
return item;
}
@NotNull
public Iterator<Byte> iterator() {
return new RingBufferIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class RingBufferIterator implements Iterator<Byte> {
private int i = 0;
public boolean hasNext() {
return i < size();
}
public void remove() {
throw new UnsupportedOperationException();
}
public Byte next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return buffer[i++];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment