Package kvd.common

Class ByteRingBuffer

java.lang.Object
kvd.common.ByteRingBuffer

public class ByteRingBuffer extends Object
A ring buffer (circular buffer, FIFO) for bytes.

All methods of this class are non-blocking and not synchronized (not thread-safe).

  • Constructor Summary

    Constructors
    Constructor
    Description
    ByteRingBuffer(int size)
    Creates a ring buffer.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Clears the ring buffer.
    void
    discard(int len)
    Discards the oldest len bytes within the ring buffer.
    int
    Returns the number of free bytes within the ring buffer.
    int
    Returns the size of the ring buffer.
    int
    Returns the number of used bytes within the ring buffer.
    int
    read(byte[] buf)
    Reads data from the ring buffer.
    int
    read(byte[] buf, int pos, int len)
    Reads data from the ring buffer.
    void
    resize(int newSize)
    Resizes the ring buffer by preserving it's data.
    int
    write(byte[] buf)
    Writes data to the ring buffer.
    int
    write(byte[] buf, int pos, int len)
    Writes data to the ring buffer.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • ByteRingBuffer

      public ByteRingBuffer(int size)
      Creates a ring buffer.
  • Method Details

    • resize

      public void resize(int newSize)
      Resizes the ring buffer by preserving it's data.

      If the new size is not enough to keep all used data in the ring buffer, the excess old data is discarded.

    • getSize

      public int getSize()
      Returns the size of the ring buffer.
    • getFree

      public int getFree()
      Returns the number of free bytes within the ring buffer.
    • getUsed

      public int getUsed()
      Returns the number of used bytes within the ring buffer.
    • clear

      public void clear()
      Clears the ring buffer.
    • discard

      public void discard(int len)
      Discards the oldest len bytes within the ring buffer. This has the same effect as calling read(new byte[len], 0, len).
      Parameters:
      len - The number of bytes to be discarded.
    • write

      public int write(byte[] buf, int pos, int len)
      Writes data to the ring buffer.
      Returns:
      The number of bytes written. This is guaranteed to be min(len, getFree()).
    • write

      public int write(byte[] buf)
      Writes data to the ring buffer.

      Convenience method for: write(buf, 0, buf.length)

    • read

      public int read(byte[] buf, int pos, int len)
      Reads data from the ring buffer.
      Returns:
      The number of bytes read. This is guaranteed to be min(len, getUsed()).
    • read

      public int read(byte[] buf)
      Reads data from the ring buffer.

      Convenience method for: read(buf, 0, buf.length)