sized_data/lib.rs
1//! Sized data trait implementation for Solana programs using Anchor framework
2//!
3//! This crate provides a trait and derive macro for calculating struct sizes at compile time,
4//! which is particularly useful when working with Solana account initialization.
5//!
6//! # Example
7//!
8//! ```rust
9//! use sized_data::SizedData;
10//! use anchor_lang::prelude::*;
11//!
12//! #[derive(SizedData)]
13//! pub struct UserAccount {
14//! pub authority: Pubkey,
15//! pub counter: u64,
16//! }
17//!
18//! #[derive(Accounts)]
19//! pub struct Initialize<'info> {
20//! #[account(
21//! init,
22//! payer = user,
23//! space = UserAccount::size_padded()
24//! )]
25//! pub user_account: Account<'info, UserAccount>,
26//! #[account(mut)]
27//! pub user: Signer<'info>,
28//! pub system_program: Program<'info, System>,
29//! }
30//! ```
31
32use anchor_lang::prelude::Pubkey;
33
34pub use sized_data_derive::*;
35
36/// A trait for types that can calculate their size at compile time.
37///
38/// Used primarily with Anchor accounts to determine required space allocation.
39/// The trait provides two methods:
40/// - `size()`: Returns the raw size of the type
41/// - `size_padded()`: Returns the size including Anchor's 8-byte discriminator
42///
43/// # Examples
44///
45/// ```rust
46/// use sized_data::SizedData;
47/// use anchor_lang::prelude::*;
48///
49/// #[derive(SizedData)]
50/// pub struct UserAccount {
51/// pub authority: Pubkey, // 32 bytes
52/// pub counter: u64, // 8 bytes
53/// }
54///
55/// assert_eq!(UserAccount::size(), 40); // Raw size
56/// assert_eq!(UserAccount::size_padded(), 48); // Including discriminator
57/// ```
58pub trait SizedData {
59 /// Returns the raw size of the type in bytes
60 fn size() -> usize;
61
62 /// Returns the size including Anchor's 8-byte discriminator
63 fn size_padded() -> usize {
64 8 + Self::size()
65 }
66}
67
68impl SizedData for u64 {
69 fn size() -> usize {
70 8
71 }
72}
73
74impl SizedData for [u8; 32] {
75 fn size() -> usize {
76 32
77 }
78}
79
80impl SizedData for Pubkey {
81 fn size() -> usize {
82 32
83 }
84}
85
86impl SizedData for u8 {
87 fn size() -> usize {
88 1
89 }
90}