I have what I consider to be a small chicken/egg problem.
I have some working code that makes a buffer-layout
Structure
, adapted from this example on SolDev.
The code then makes a Buffer
, and uses the structure.encode()
to encode some data into the buffer using the format of the Structure
.
Right now, though, the code sets the size of the buffer to a static number. This seems suboptimal: I'd to make the function calculate the required size from the data to encode.
How can I calculate the size of a borch buffer without having to fill it with data first?
import { struct, u8, str } from "@coral-xyz/borsh";
import { log } from "console";
const structure = struct([
u8("variant"),
str("title"),
u8("rating"),
str("description"),
]);
const serialize = (
title: string,
rating: number,
description: string
): Buffer => {
// This is the part of the code that I would like to be able to generate based on the size of the data
// rather than hardcoding it
const buffer = Buffer.alloc(1000);
structure.encode(
{
variant: 0,
title,
rating,
description,
},
buffer
);
return buffer.slice(0, structure.getSpan(buffer));
};
let title: string = "Silence of the Lambs";
let rating: number = 5;
let description: string =
"A young FBI cadet must confide in an incarcerated and manipulative killer to receive his help on catching another serial killer who skins his victims.";
const serialized = serialize(title, rating, description);
log(serialized.toString("hex"));