buffer creates a read-only binary array from a string, and allows reads of data types from it. All functions throw errors in case something goes wrong.
It's just one file, either add it to your project or build a loadable Lua module with:
$ gcc -std=c99 -O2 -Werror -Wall -Wpedantic -shared -fPIC -o buffer.so buffer.c
buffer.new
creates the buffer object, with the read position set to 0:
buffer.new(
value, -- String whose contents will be available for reading via the buffer.
)
Example:
local buffer = require 'buffer'
local buf = assert(buffer.new('abcd'))
Returns the created buffer, or nil
plus an error message in case of errors.
Reads a data type from the buffer, starting with the byte at the current read position. Allowed data types are:
sb
: Signed byteub
: Unsigned byteswl
: Signed word (16 bits) in little-endianswb
: Signed word in big-endianuwl
: Unsigned word in little-endianuwb
: Unsigned word in big-endiansdl
: Signed double word (32 bits) in little-endiansdb
: Signed double word in big-endianudl
: Unsigned double word in little-endianudb
: Unsigned double word in big-endiansql
: Signed quad word (64 bits) in little-endiansqb
: Signed quad word in big-endianuql
: Unsigned quad word in little-endianuqb
: Unsigned quad word in big-endianfl
: Float in little-endianfb
: Float in big-endiandl
: Double in little-endiandb
: Double in big-endiansw
: Signed word in the current machine's endian modeuw
: Unsigned word in the current machine's endian modesd
: Signed double word in the current machine's endian modeud
: Unsigned double word in the current machine's endian modesq
: Signed quad word in the current machine's endian modeuq
: Unsigned quad word in the current machine's endian modef
: Float in the current machine's endian moded
: Double in the current machine's endian model
: Reads an entire line terminated with the ASCII character\n'
- A number: Returns a string with that many characters
The read position is incremented according to the type read.
Example:
local buffer = require 'buffer'
local buf = assert(buffer.new('\x12\x34\x56\x78'))
print(string.format('%x', assert(buf:read('udb')))) -- prints 12345678
Returns the read result, or nil
plus an error message in case of errors.
Changes the current read position. The way offset
is applied depends on the whence
parameter:
"set"
(default if omitted): The new read position will be the value ofoffset
"cur"
: The new read position will beoffset
added to the current read position"end"
: The new read position will be the size of the buffer subtracted fromoffset
Returns the new absolute read position, or nil
plus an error message in case of errors.
Returns the current read position.
Returns the buffer size.
Returns a piece of a buffer as a new buffer, starting at the original buffer begin
position, with size
bytes, or nil
plus an error message in case of errors.
- 1.0.0
- First public release
MIT, enjoy.