anchor_idl/
lib.rs

1//! Generates Rust code from an Anchor IDL.
2
3pub use anchor_lang_idl_spec::*;
4
5mod account;
6mod event;
7mod fields;
8mod instruction;
9mod program;
10mod state;
11mod typedef;
12
13pub use account::*;
14pub use event::*;
15pub use instruction::*;
16pub use program::*;
17pub use state::*;
18pub use typedef::*;
19
20/// Version of anchor-idl.
21pub const GEN_VERSION: Option<&str> = option_env!("CARGO_PKG_VERSION");
22
23/// Converts an [IdlType] to a [String] of the Rust representation.
24pub fn ty_to_rust_type(ty: &IdlType) -> String {
25    match ty {
26        IdlType::Bool => "bool".to_string(),
27        IdlType::U8 => "u8".to_string(),
28        IdlType::I8 => "i8".to_string(),
29        IdlType::U16 => "u16".to_string(),
30        IdlType::I16 => "i16".to_string(),
31        IdlType::U32 => "u32".to_string(),
32        IdlType::I32 => "i32".to_string(),
33        IdlType::F32 => "f32".to_string(),
34        IdlType::U64 => "u64".to_string(),
35        IdlType::I64 => "i64".to_string(),
36        IdlType::F64 => "f64".to_string(),
37        IdlType::U128 => "u128".to_string(),
38        IdlType::I128 => "i128".to_string(),
39        IdlType::Bytes => "Vec<u8>".to_string(),
40        IdlType::String => "String".to_string(),
41        IdlType::Pubkey => "Pubkey".to_string(),
42        IdlType::Option(inner) => format!("Option<{}>", ty_to_rust_type(inner)),
43        IdlType::Vec(inner) => format!("Vec<{}>", ty_to_rust_type(inner)),
44        IdlType::Array(ty, size) => match size {
45            IdlArrayLen::Generic(name) => {
46                format!("[{}; {}]", ty_to_rust_type(ty), *name)
47            }
48            IdlArrayLen::Value(size) => {
49                format!("[{}; {}]", ty_to_rust_type(ty), *size)
50            }
51        },
52        IdlType::Defined { name, generics: _ } => name.to_string(),
53        IdlType::U256 => todo!(),
54        IdlType::I256 => todo!(),
55        IdlType::Generic(_) => todo!(),
56        _ => todo!(),
57    }
58}