pub trait MaxSerializedLen {
const MAX_SERIALIZED_LEN: usize;
}Expand description
Trait that provides the maximum length of the serialized byte stream of a borsh-serializable data structure.
Useful when allocating space for a Solana account upon creation.
§Examples
use agsol_common::MaxSerializedLen;
use borsh::{BorshSerialize, BorshDeserialize};
use solana_program::pubkey::Pubkey;
#[derive(BorshSerialize, BorshDeserialize, MaxSerializedLen)]
struct FooStruct {
foo: u64, // max len: 8
bar: i32, // max len: 4
}
#[derive(BorshSerialize, BorshDeserialize, MaxSerializedLen)]
struct BarStruct {
foo: [u8; 32], // max len: 32
#[len(4 + 8 * 2)]
bar: Vec<u16>, // max len: 20
baz: Option<FooStruct>, // max len: 13
}
#[derive(BorshSerialize, BorshDeserialize, MaxSerializedLen)]
enum FooEnum {
Foo { // max len: 40 + 1
a: u64,
b: Pubkey,
},
Bar, // max len: 1
Baz(Option<Pubkey>), // max len: 1 + 1 + 32
#[len(200)]
Quux(String), // max len: 1 + 200
}
assert_eq!(FooStruct::MAX_SERIALIZED_LEN, 12);
assert_eq!(BarStruct::MAX_SERIALIZED_LEN, 65);
assert_eq!(FooEnum::MAX_SERIALIZED_LEN, 201);§Notes
Note, that for enums with more than ~15 variants, the compiler hangs due to
the way the maximum lengths of the variants are computed. Therefore, it is
not recommended to derive MaxSerializedLen for enums like that, rather it
should be implemented manually.
Required Associated Constants§
const MAX_SERIALIZED_LEN: usize
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".