Prosody IM Website


file doc/developers/util/ringbuffer.md in changeset 94f5b7dfbaf6

View latest ↓ Download file

line wrap: on
line source

---
abstract: A ringbuffer for binary data
title: 'util.ringbuffer'
---

This library provides a first-in-first-out interface for raw bytes. Its
interface is similar to file handles, having read and write methods. It
is similar to [util.queue](/doc/developers/util/queue) but deals with
raw bytes instead of arbitrary objects.

An example:

``` {.code .lua}
local ringbuffer = require"util.ringbuffer";
 
local buf = ringbuffer.new(1024); -- defaults to page size, probably 4096 bytes
 
print(buf:size()) --> size of the buffer: 1024
print(buf:write("hello")) --> 5 bytes written
print(buf:read(5)) --> hello
```

# Module reference {#module_reference}

## new(size) {#new_size}

Creates a new ringbuffer capable of holding `size` bytes.

# Methods

## :read(length, peek) {#read_length_peek}

Returns the next `length` bytes from the buffer. If `peek` is true, then
the bytes will stay in the buffer.

## :write(string) {#write_string}

Writes the bytes from `string` into the buffer. On success, the number
of bytes written are returned. If there is not enough free space in the
buffer, then `nil` is returned.

## :size()

Returns the total size of the buffer, same as given to `new()`

## :length()

Returns the number of bytes currently added to the buffer. The `#`
operator also returns this.

## :free()

Returns the number of bytes that can be written to the buffer before it
becomes full. Essentially `buf:size() - buf:length()`.

## :find(needle) {#find_needle}

Searches for the string `needle` in the buffer, and returns the distance
to the first match, or `nil` if no match is found.

## :readuntil(needle) {#readuntil_needle}

Searches for, and returns data until and including the next instance of
the string `needle` in the buffer.

## :byte(a[, b]) {#byte_a_b}

Equivalent to Lua's string.byte. Returns the value of the byte at index
'a' as a number. If 'b' is supplied, returns multiple values for each
byte in the range a to b, where the indices are treated as in string.sub.

## :sub(a[, b]) {#sub_a_b}

Equivalent to Lua's string.sub. Returns a substring selected by the a and
b parameters, interpreted according to the same rules as Lua's string.sub.

## :discard(length)

Consumes `length` bytes from the buffer without returning them.