0

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"));

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • This unfortunately doesn't answer the question, but on the Rust side, there's a function called `get_instance_packed_len` which does exactly this https://github.com/solana-labs/solana/blob/de4ff348b404be5bba2ee62463d785fb070a0a57/sdk/program/src/borsh.rs#L108 -- maybe you can write your own function which intercepts the serializing to just increment a counter? – Jon C Jul 24 '23 at 18:42

0 Answers0