Home

Awesome

Borsh in C++   C++ 17 Ref badge

borsh-cpp is a single header C++ implementation of the Borsh binary serialization format.

Borsh stands for Binary Object Representation Serializer for Hashing. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification.

Example

#include "BorshCpp.hpp"

int main()
{
	bool cArray[2] = {true, false};
	auto initList = {"1", "2"};

	std::vector<uint8_t> dynamicArray = {
		34,
		85,
		255
	};

	BorshEncoder encoder;
	encoder
		.Encode(
			/* Integers */
			(uint8_t)0xff,
			(uint16_t)0xffff,
			(uint32_t)0xffffffff,
			
			/* Floats */
			230.121312f,
			230.121312,

			/* Bools */
			true,

			/* Strings */
			"Hola mundo!!!", // suppport ascii
			u8"Hola mundo!!!🤓", // and utf8 only as literals!!!!!

			/* C Array */
			std::pair{cArray, 2},

			/* Initializer List */
			initList,

			/* Vectors */
			dynamicArray
		);

	for (auto c : encoder.GetBuffer())
	{
		printf("%d ", c);
	}
	printf("\n");

	auto buffer = encoder.GetBuffer();
	BorshDecoder decoder;

	// hold the decoded data
	uint8_t uInt8{};
	uint16_t uInt16{};
	uint32_t uInt32{};
	float f32{};
	double f64{};
	bool b{};
	std::string str{};
	std::string u8Str{};

	decoder.Decode(
		buffer.data(),
		uInt8, uInt16, uInt32, f32, f64, b, str, u8Str
	);

	std::cout << 
		(uint32_t)uInt8 << " " <<
		uInt16 << " " <<
		uInt32 << " " <<
		f32 << " " <<
		f64 << " " <<
		b << " " <<
		str << " " <<
		u8Str << " " <<
		"\n";
}

Types

BorshC++
booltrue or false
u8 integeruint8_t
u16 integeruint16_t
u32 integeruint32_t
u64 integeruint64_t
u128 integerNot supported
i8 integerint8_t
i16 integerint16_t
i32 integerint32_t
i64 integerint64_t
i128 integerNot supported
f32 floatfloat
f64 floatdouble
fixed-size arraystd::initializer_list<T>
fixed-size arrayT*, size_t size
dynamic arraystd::vector<T>
UTF-8 stringstd::string(u8"🤓")
UTF-8 stringu8"🤓"
optionNot supported
setNot supported
mapNot supported
structsNot supported
enumNot supported

Limitations

For now only support serialization for all previous types, but for decode only a few for now