|
| 1 | +use steel::*; |
| 2 | + |
| 3 | +use crate::error::{CloseAccountError, CloseAccountResult}; |
| 4 | + |
| 5 | +/// An enum which is used to derive a discriminator for the user account. |
| 6 | +#[repr(u8)] |
| 7 | +#[derive(Clone, Copy, Debug, Eq, PartialEq, IntoPrimitive, TryFromPrimitive)] |
| 8 | +pub enum UserAccount { |
| 9 | + /// The user is represented by a discriminator of `0` |
| 10 | + User = 0, |
| 11 | +} |
| 12 | + |
| 13 | +/// The user Account structure which stores a |
| 14 | +/// `name` as bytes with max array length of u64 due to the |
| 15 | +/// requirement for memory alignment since 64 is a factor of 8. |
| 16 | +#[repr(C)] |
| 17 | +#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)] |
| 18 | +pub struct User { |
| 19 | + /// The name string stored as bytes. |
| 20 | + /// The `&str` is converted into bytes and copied upto |
| 21 | + /// the length of the bytes, if the bytes are not 64, it |
| 22 | + /// pads with zeroes upto 64, if it is more than 64 an error |
| 23 | + /// is returned. |
| 24 | + pub name: [u8; 64], |
| 25 | +} |
| 26 | + |
| 27 | +impl User { |
| 28 | + /// Seed for the [User] used to in PDA generation |
| 29 | + pub const SEED_PREFIX: &'static str = "USER"; |
| 30 | + |
| 31 | + /// Create a new user, convert the name into bytes |
| 32 | + /// and add those bytes to a 64 byte array |
| 33 | + pub fn new(name: &str) -> CloseAccountResult<Self> { |
| 34 | + let name_bytes = name.as_bytes(); |
| 35 | + |
| 36 | + Self::check_length(name_bytes)?; |
| 37 | + |
| 38 | + let mut name = [0u8; 64]; |
| 39 | + name[0..name_bytes.len()].copy_from_slice(name_bytes); |
| 40 | + |
| 41 | + Ok(Self { name }) |
| 42 | + } |
| 43 | + |
| 44 | + /// Converts the byte array into a UTF-8 [str] |
| 45 | + /// using the `trim_end_matches("\0")` of [str] method |
| 46 | + /// to remove padded zeroes if any. Padded zeroes are |
| 47 | + /// represented by `\0` |
| 48 | + pub fn to_string(&self) -> CloseAccountResult<String> { |
| 49 | + let value = |
| 50 | + core::str::from_utf8(&self.name).map_err(|_| CloseAccountError::OnlyUtf8IsSupported)?; |
| 51 | + |
| 52 | + Ok(value.trim_end_matches("\0").to_string()) |
| 53 | + } |
| 54 | + |
| 55 | + fn check_length(bytes: &[u8]) -> CloseAccountResult<()> { |
| 56 | + if bytes.len() > 64 { |
| 57 | + return Err(CloseAccountError::MaxNameLengthExceeded); |
| 58 | + } |
| 59 | + |
| 60 | + Ok(()) |
| 61 | + } |
| 62 | + |
| 63 | + /// Generate a PDA from the [Self::SEED_PREFIX] constant |
| 64 | + /// and the payer public key. This returns a tuple struct |
| 65 | + /// ([Pubkey], [u8]) |
| 66 | + pub fn pda(payer: Pubkey) -> (Pubkey, u8) { |
| 67 | + Pubkey::try_find_program_address( |
| 68 | + &[Self::SEED_PREFIX.as_bytes(), payer.as_ref()], |
| 69 | + &crate::id(), |
| 70 | + ) |
| 71 | + .unwrap() |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +account!(UserAccount, User); |
0 commit comments