Skip to main content

wrapped_decimal/
lib.rs

1//! `wrapped-decimal` provides [`WrappedDecimal`], a fixed-size wrapper around
2//! [`rust_decimal::Decimal`] with a stable 16-byte representation.
3//!
4//! This is useful for Solana account/state layouts that require predictable,
5//! POD-safe binary encoding.
6
7use bytemuck::{Pod, Zeroable};
8use rust_decimal::Decimal;
9
10#[derive(Clone, Copy, Zeroable, Pod)]
11#[cfg_attr(
12    feature = "anchor",
13    derive(
14        anchor_lang::InitSpace,
15        anchor_lang::prelude::AnchorSerialize,
16        anchor_lang::prelude::AnchorDeserialize
17    )
18)]
19#[repr(C)]
20/// A fixed-size, POD-safe wrapper around [`rust_decimal::Decimal`].
21///
22/// The decimal is stored as the 16-byte serialized representation from
23/// `rust_decimal`, making this type suitable for account/state layouts that
24/// require stable byte size.
25pub struct WrappedDecimal([u8; 16]);
26
27impl From<Decimal> for WrappedDecimal {
28    /// Serializes a [`Decimal`] into its 16-byte wrapped representation.
29    fn from(d: Decimal) -> Self {
30        Self(d.serialize())
31    }
32}
33
34impl From<WrappedDecimal> for Decimal {
35    /// Deserializes the wrapped 16-byte representation back into a [`Decimal`].
36    fn from(w: WrappedDecimal) -> Self {
37        Decimal::deserialize(w.0)
38    }
39}