substrate_stellar_sdk/xdr/impls/
asset_code.rs1use core::convert::AsRef;
2
3use crate::{AssetCode, StellarSdkError};
4
5impl AssetCode {
6 pub fn new<T: AsRef<[u8]>>(str: T) -> Result<Self, StellarSdkError> {
7 let str = str.as_ref();
8 if str.len() > 12 {
9 return Err(StellarSdkError::AssetCodeTooLong)
10 }
11
12 if !str.iter().all(|char| {
13 let char = char::from(*char);
14 char.is_ascii_alphanumeric()
15 }) {
16 return Err(StellarSdkError::InvalidAssetCodeCharacter)
17 }
18
19 if str.len() <= 4 {
20 let mut asset_code_array: [u8; 4] = [0; 4];
21 asset_code_array[..str.len()].copy_from_slice(str);
22 Ok(AssetCode::AssetTypeCreditAlphanum4(asset_code_array))
23 } else {
24 let mut asset_code_array: [u8; 12] = [0; 12];
25 asset_code_array[..str.len()].copy_from_slice(str);
26 Ok(AssetCode::AssetTypeCreditAlphanum12(asset_code_array))
27 }
28 }
29}