ringbuffer

package module
v0.0.0-...-bab516b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 5 Imported by: 14

README

ringbuffer

License GoDoc Go Report Card coveralls

A circular buffer (ring buffer) in Go, implemented io.ReaderWriter interface

wikipedia

Usage

package main

import (
	"fmt"

	"github.com/smallnest/ringbuffer"
)

func main() {
	rb := ringbuffer.New(1024)

	// write
	rb.Write([]byte("abcd"))
	fmt.Println(rb.Length())
	fmt.Println(rb.Free())

	// read
	buf := make([]byte, 4)
	rb.Read(buf)
	fmt.Println(string(buf))
}

It is possible to use an existing buffer with by replacing New with NewBuffer.

Blocking vs Non-blocking

The default behavior of the ring buffer is non-blocking, meaning that reads and writes will return immediately with an error if the operation cannot be completed. If you want to block when reading or writing, you must enable it:

	rb := ringbuffer.New(1024).SetBlocking(true)

Enabling blocking will cause the ring buffer to behave like a buffered io.Pipe.

Regular Reads will block until data is available, but not wait for a full buffer. Writes will block until there is space available and writes bigger than the buffer will wait for reads to make space.

TryRead and TryWrite are still available for non-blocking reads and writes.

To signify the end of the stream, close the ring buffer from the writer side with rb.CloseWriter()

Either side can use rb.CloseWithError(err error) to signal an error and close the ring buffer. Any reads or writes will return the error on next call.

In blocking mode errors are stateful and the same error will be returned until rb.Reset() is called.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrTooMuchDataToWrite = errors.New("too much data to write")
	ErrIsFull             = errors.New("ringbuffer is full")
	ErrIsEmpty            = errors.New("ringbuffer is empty")
	ErrIsNotEmpty         = errors.New("ringbuffer is not empty")
	ErrAcquireLock        = errors.New("unable to acquire lock")
	ErrWriteOnClosed      = errors.New("write on closed ringbuffer")
)

Functions

This section is empty.

Types

type RingBuffer

type RingBuffer struct {
	// contains filtered or unexported fields
}

RingBuffer is a circular buffer that implement io.ReaderWriter interface. It operates like a buffered pipe, where data written to a RingBuffer and can be read back from another goroutine. It is safe to concurrently read and write RingBuffer.

Example
rb := New(1024)
rb.Write([]byte("abcd"))
fmt.Println(rb.Length())
fmt.Println(rb.Free())
buf := make([]byte, 4)

rb.Read(buf)
fmt.Println(string(buf))
Output:

4
1020
abcd

func New

func New(size int) *RingBuffer

New returns a new RingBuffer whose buffer has the given size.

func NewBuffer

func NewBuffer(b []byte) *RingBuffer

NewBuffer returns a new RingBuffer whose buffer is provided.

func (*RingBuffer) Bytes

func (r *RingBuffer) Bytes(dst []byte) []byte

Bytes returns all available read bytes. It does not move the read pointer and only copy the available data. If the dst is big enough it will be used as destination, otherwise a new buffer will be allocated.

func (*RingBuffer) Capacity

func (r *RingBuffer) Capacity() int

Capacity returns the size of the underlying buffer.

func (*RingBuffer) CloseWithError

func (r *RingBuffer) CloseWithError(err error)

CloseWithError closes the writer; reads will return no bytes and the error err, or EOF if err is nil.

CloseWithError never overwrites the previous error if it exists and always returns nil.

func (*RingBuffer) CloseWriter

func (r *RingBuffer) CloseWriter()

CloseWriter closes the writer. Reads will return any remaining bytes and io.EOF.

func (*RingBuffer) Flush

func (r *RingBuffer) Flush() error

Flush waits for the buffer to be empty and fully read. If not blocking ErrIsNotEmpty will be returned if the buffer still contains data.

func (*RingBuffer) Free

func (r *RingBuffer) Free() int

Free returns the length of available bytes to write.

func (*RingBuffer) IsEmpty

func (r *RingBuffer) IsEmpty() bool

IsEmpty returns this ringbuffer is empty.

func (*RingBuffer) IsFull

func (r *RingBuffer) IsFull() bool

IsFull returns this ringbuffer is full.

func (*RingBuffer) Length

func (r *RingBuffer) Length() int

Length return the length of available read bytes.

func (*RingBuffer) Read

func (r *RingBuffer) Read(p []byte) (n int, err error)

Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more. When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.

func (*RingBuffer) ReadByte

func (r *RingBuffer) ReadByte() (b byte, err error)

ReadByte reads and returns the next byte from the input or ErrIsEmpty.

func (*RingBuffer) Reset

func (r *RingBuffer) Reset()

Reset the read pointer and writer pointer to zero.

func (*RingBuffer) SetBlocking

func (r *RingBuffer) SetBlocking(block bool) *RingBuffer

SetBlocking sets the blocking mode of the ring buffer. If block is true, Read and Write will block when there is no data to read or no space to write. If block is false, Read and Write will return ErrIsEmpty or ErrIsFull immediately. By default, the ring buffer is not blocking. This setting should be called before any Read or Write operation or after a Reset.

func (*RingBuffer) TryRead

func (r *RingBuffer) TryRead(p []byte) (n int, err error)

TryRead read up to len(p) bytes into p like Read but it is not blocking. If it has not succeeded to acquire the lock, it return 0 as n and ErrAcquireLock.

func (*RingBuffer) TryWrite

func (r *RingBuffer) TryWrite(p []byte) (n int, err error)

TryWrite writes len(p) bytes from p to the underlying buf like Write, but it is not blocking. If it has not succeeded to accquire the lock, it return 0 as n and ErrAcquireLock.

func (*RingBuffer) TryWriteByte

func (r *RingBuffer) TryWriteByte(c byte) error

TryWriteByte writes one byte into buffer without blocking. If it has not succeeded to acquire the lock, it return ErrAcquireLock.

func (*RingBuffer) WithCancel

func (r *RingBuffer) WithCancel(ctx context.Context) *RingBuffer

WithCancel sets a context to cancel the ring buffer. When the context is canceled, the ring buffer will be closed with the context error. A goroutine will be started and run until the provided context is canceled.

func (*RingBuffer) Write

func (r *RingBuffer) Write(p []byte) (n int, err error)

Write writes len(p) bytes from p to the underlying buf. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. If blocking n < len(p) will be returned only if an error occurred. Write returns a non-nil error if it returns n < len(p). Write will not modify the slice data, even temporarily.

func (*RingBuffer) WriteByte

func (r *RingBuffer) WriteByte(c byte) error

WriteByte writes one byte into buffer, and returns ErrIsFull if buffer is full.

func (*RingBuffer) WriteCloser

func (r *RingBuffer) WriteCloser() io.WriteCloser

WriteCloser returns a WriteCloser that writes to the ring buffer. When the returned WriteCloser is closed, it will wait for all data to be read before returning.

func (*RingBuffer) WriteString

func (r *RingBuffer) WriteString(s string) (n int, err error)

WriteString writes the contents of the string s to buffer, which accepts a slice of bytes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL