spl_type_length_value/
length.rs

1//! Module for the length portion of a Type-Length-Value structure
2use {
3    bytemuck::{Pod, Zeroable},
4    solana_program_error::ProgramError,
5    spl_pod::primitives::PodU32,
6};
7
8/// Length in TLV structure
9#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)]
10#[repr(transparent)]
11pub struct Length(PodU32);
12impl TryFrom<Length> for usize {
13    type Error = ProgramError;
14    fn try_from(n: Length) -> Result<Self, Self::Error> {
15        Self::try_from(u32::from(n.0)).map_err(|_| ProgramError::AccountDataTooSmall)
16    }
17}
18impl TryFrom<usize> for Length {
19    type Error = ProgramError;
20    fn try_from(n: usize) -> Result<Self, Self::Error> {
21        u32::try_from(n)
22            .map(|v| Self(PodU32::from(v)))
23            .map_err(|_| ProgramError::AccountDataTooSmall)
24    }
25}