varbinary
Since 3.0.0
The varbinary module provides functions for operating variable-length binary objects in Lua. It provides functions for creating varbinary objects, checking their type, and also defines basic operators on such objects.
Example:
local varbinary = require('varbinary')
-- Create a varbinary object
local bin = varbinary.new('data')
local bin_hex = varbinary.new('\xFF\xFE')
-- Check whether a value is a varbinary object
varbinary.is(bin) -- true
varbinary.is(bin_hex) -- true
varbinary.is(100) -- false
varbinary.is('data') -- false
-- Check varbinary objects equality
print(bin == varbinary.new('data')) -- true
print(bin == 'data') -- true
print(bin ~= 'data1') -- true
print(bin_hex ~= '\xFF\xFE') -- false
-- Check varbinary objects length
print(#bin) -- 4
print(#bin_hex) -- 2
-- Print string representation
print(tostring(bin)) -- data
Encoding varbinary objects
varbinary objects preserve their binary type when encoded by the built-in MsgPack and YAML encoders. See the difference with strings:
- String to MsgPack:
tarantool> msgpack.encode('\xFF\xFE')
---
- "\xA2\xFF\xFE"
...
varbinaryto MsgPack:
tarantool> msgpack.encode(varbinary.new('\xFF\xFE'))
---
- "\xC4\x02\xFF\xFE"
...
- String to YAML:
tarantool> '\xFF\xFE'
---
- "\xFF\xFE"
...
varbinaryto YAML:
tarantool> varbinary.new('\xFF\xFE')
---
- !!binary //4=
...
JSON does not support the binary type, so varbinary objects are encoded as plain strings in JSON:
tarantool> json.encode('\xFF\xFE')
---
- "\"\xFF\xFE\""
...
tarantool> json.encode(varbinary.new('\xFF\xFE'))
---
- "\"\xFF\xFE\""
...
Decoding binary data to varbinary objects
The built-in decoders also decode binary data fields (fields with the binary tag in YAML and the MP_BIN type in MsgPack) to varbinary objects by default:
tarantool> varbinary.is(msgpack.decode('\xC4\x02\xFF\xFE'))
---
- true
...
tarantool> varbinary.is(yaml.decode('!!binary //4='))
---
- true
...
Important: This behavior is different from what it was before Tarantool 3.0. In earlier versions, such fields were decoded to plain strings. To return to this behavior, use the compat option binary_data_decoding.
Methods2
function M.is(obj: any) -> result boolean
Check that the given object is a varbinary object.
objanyan object to check.
resultbooleanwhether the given object is of
varbinarytype.
function M.new(data: string, size: integer) -> bin varbinary_object
Create a new varbinary object.
With no arguments, creates an empty varbinary object. With a string argument, creates an object from the string data. With a varbinary object, creates a copy of it. With a cdata pointer and size, creates an object from that memory region.
function M.new() -> varbinary_objectfunction M.new(obj: varbinary_object) -> varbinary_objectfunction M.new(data: ffi.cdata*, size: integer) -> varbinary_objectdatastringa string object.
sizeintegerobject size in bytes, mandatory if
datais a pointer.
binvarbinary_objecta
varbinaryobject containing the data.