neo_solidity/
utils.rs

1//! Shared Utility Functions
2//!
3//! Common utilities used across the compiler.
4
5/// Convert a Solidity type string to its canonical form for ABI encoding.
6///
7/// Handles special cases like `struct Foo` and `enum Bar` by extracting
8/// just the type name.
9///
10/// # Examples
11/// ```
12/// use neo_solidity::utils::canonical_param_type;
13/// assert_eq!(canonical_param_type("uint256"), "uint256");
14/// assert_eq!(canonical_param_type("struct MyStruct"), "MyStruct");
15/// assert_eq!(canonical_param_type("enum MyEnum"), "MyEnum");
16/// ```
17pub fn canonical_param_type(ty: &str) -> String {
18    let mut parts = ty.split_whitespace();
19    match parts.next() {
20        Some("struct" | "enum") => parts.next().unwrap_or_default().to_string(),
21        Some(first) => first.to_string(),
22        None => String::new(),
23    }
24}
25
26/// Simple canonical type extraction (first word only).
27///
28/// Use this when struct/enum special handling is not needed.
29pub fn canonical_param_type_simple(ty: &str) -> String {
30    ty.split_whitespace().next().unwrap_or_default().to_string()
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn test_canonical_param_type() {
39        assert_eq!(canonical_param_type("uint256"), "uint256");
40        assert_eq!(canonical_param_type("struct MyStruct"), "MyStruct");
41        assert_eq!(canonical_param_type("enum MyEnum"), "MyEnum");
42        assert_eq!(canonical_param_type("address payable"), "address");
43        assert_eq!(canonical_param_type(""), "");
44    }
45
46    #[test]
47    fn test_canonical_param_type_simple() {
48        assert_eq!(canonical_param_type_simple("uint256"), "uint256");
49        assert_eq!(canonical_param_type_simple("struct MyStruct"), "struct");
50        assert_eq!(canonical_param_type_simple("address payable"), "address");
51    }
52}