flatbuffers_rust/flatbuffers/
flatbuffer_manager.rs

1#[macro_export]
2macro_rules! register_struct_info {
3    (struct $name:ident { $($fname:ident : $ftype:ty),* }, $vec:expr) => {
4        struct $name {}
5
6        impl $name {
7            fn get_fields_info<'a>(names_types: &mut Vec<StructInfo>) {
8                let mut child_names_types = Vec::new();
9                $( 
10                    child_names_types.push(
11                        FieldInfo {
12                            field_name: stringify!($fname), 
13                            field_type: stringify!($ftype)
14                        }
15                    ); 
16                )*;
17                let (prefix, struct_name) = stringify!($name).split_at(2);
18                names_types.push(
19                    StructInfo {
20                        struct_name: struct_name,
21                        fields: child_names_types
22                    }
23                );
24            }
25        }
26        $name::get_fields_info(&mut $vec);
27    };
28}
29// #[macro_export]
30// macro_rules! register_instance_info {
31//     () => ()
32// }
33// #[macro_export]
34// macro_rules! find_field_position_vec {
35//     ($name:ident :: $($field:ident).*, $fields:expr) => {
36//         // let mut fields = Vec::new(); // vec<&str>
37//         $fields.push(stringify!($name));
38//         $( $fields.push(stringify!($field)); )*
39//         // 先翻转 
40//         $fields.reverse();
41//         // $manager.field_position_vec(&mut fields);
42//     }
43// }
44#[derive(Debug, Clone)]
45pub struct StructInfo<'a> {
46    pub struct_name: &'a str, // 结构体类型名
47    pub fields: Vec<FieldInfo<'a>> // 结构体字段信息
48}
49impl<'a> StructInfo<'a> {
50    pub fn find_field(&self, name: &str) -> Result<(&FieldInfo, usize), String> {
51        let mut position = 0;
52        let len = self.fields.len();
53        let fields = self.fields.clone();
54        for i in 0..len {
55            if fields[i].field_name.eq(name) {
56                return Ok((&self.fields[i], i+1))
57            }
58        }
59        return Err(format!("NO field named {:?}", name));
60    }
61}
62#[derive(Debug, Clone)]
63pub struct FieldInfo<'a> {
64    pub field_name: &'a str, // 字段名
65    pub field_type: &'a str // 字段类型
66}
67
68#[derive(Debug)]
69pub struct FlatBufferManager<'a> {
70    // 存储所有结构体的信息
71    pub struct_list: Vec<StructInfo<'a>>,
72}
73impl<'a> FlatBufferManager<'a> {
74    pub fn new() -> FlatBufferManager<'a> {
75        FlatBufferManager {
76            struct_list: Vec::new()
77        }
78    }
79
80    pub fn find_struct(&self, name: &str) -> Result<&StructInfo, String> {
81        let mut struct_list = self.struct_list.clone();
82        let len = struct_list.len();
83        // println!("all structs is {}", len);
84        for i in 0..len {
85            if struct_list[i].struct_name.eq(name) {
86                return Ok(&self.struct_list[i]);
87            }
88        }
89        return Err(format!("NO struct named {:?}", name));
90    }
91    fn field_position_vec(&self, fields:&mut Vec<&str>) -> Result<Vec<usize>, String> {
92        // 先获取到第一个 字段=类名
93        let mut position_vec = Vec::new();
94        let struct_name = fields.pop().unwrap();
95        let struct_info = match self.find_struct(struct_name) {
96            Ok(info) => info, // &structinfo类型 
97            Err(e) => return Err(e),
98        };
99        // loop {
100        // 使用 RefCell 变为& -> &mut 不可行
101        // let mut rfc_struct_info = RefCell::new(struct_info);
102        let field_name = fields.pop().unwrap();
103        let rest_field = fields.len();
104        // 去寻找对应的field
105        let (field_type, p) = match struct_info.find_field(field_name) {
106            Ok((field, p)) => (field.field_type, p),
107            Err(e) => return Err(e),
108        };
109        position_vec.push(p);
110        if rest_field == 0 {
111            // 没有后面的内容了,说明成功,传数组
112            position_vec.reverse();
113            // println!("翻转一次");
114            return Ok(position_vec);
115        }
116        if field_type.eq("String") {
117            return Err(format!("{:?} has not {:?}",struct_name, fields.pop().unwrap()));
118        } else if field_type.eq("bool") {
119            return Err(format!("{:?} has not {:?}",struct_name, fields.pop().unwrap()));
120        } else {
121
122            if field_type.starts_with("List<") {
123                // 是 List<T>
124                // 将 内部的 T 解析出来
125                let (list_str, inner_type) = field_type.split_at(5);
126                let mut inner_type_string = String::from(inner_type);// T>
127                let last = inner_type_string.len() - 1;
128                inner_type_string.remove(last);
129                // 将 数字 加入vec
130                // let index = fields.pop().unwrap();
131                // position_vec.push(index.parse::<usize>());
132                self.field_position_vec_inner(inner_type_string.as_str(), fields, &mut position_vec);
133                return Ok(position_vec);
134            
135            } else {
136                self.field_position_vec_inner(field_type, fields, &mut position_vec);
137                return Ok(position_vec);
138            }
139
140            // 调用inner方法 不用翻转 在inner中翻转了
141            // self.field_position_vec_inner(field_type, fields, &mut position_vec);
142            // return Ok(position_vec);
143        }
144    }
145    fn field_position_vec_inner(&self, struct_name: &str, fields:&mut Vec<&str>, position_vec: &mut Vec<usize>) -> Result<(), String> {
146        
147        let mut field_name = "";
148        loop {
149            field_name = fields.pop().unwrap();
150            
151            match field_name.parse::<usize>() {
152                Ok(n) => { 
153                    position_vec.push(n+1); 
154                    // 考虑是否是最后一项
155                    if fields.len() == 0 {
156                        position_vec.reverse();
157                        // println!("翻转一次");
158                        return Ok(());
159                    } else {
160                        continue; 
161                    }
162                }
163                Err(e) => break,
164            };
165        }
166        let struct_info = match self.find_struct(struct_name) {
167            Ok(info) => info, // structinfo类型 
168            Err(e) => return Err(e),
169        };
170        let rest_field = fields.len();
171        // 去寻找对应的field
172        let (field_type, p) = match struct_info.find_field(field_name) {
173            Ok((field, p)) => (field.field_type, p),
174            Err(e) => return Err(e),
175        };
176        position_vec.push(p);
177        if rest_field == 0 {
178            position_vec.reverse();
179            // println!("翻转一次");
180            return Ok(());
181        }
182        if field_type.eq("String") {
183            return Err(format!("{:?} has not {:?}",struct_name, fields.pop().unwrap()));
184        } else if field_type.eq("bool") {
185            return Err(format!("{:?} has not {:?}",struct_name, fields.pop().unwrap()));
186        } else {
187            // 在这里处理List<T> 和 T 的情况
188            if field_type.starts_with("List<") {
189                
190                // 是 List<T>
191                // 将 内部的 T 解析出来
192                let (list_str, inner_type) = field_type.split_at(5);
193                let mut inner_type_string = String::from(inner_type);// T>
194                
195                let last = inner_type_string.len() - 1;
196                inner_type_string.remove(last);
197                // println!("fields now is {:?}", fields);
198                // 将 数字 加入vec
199                // let index = fields.pop().unwrap();
200                // position_vec.push(index.parse::<usize>());
201                return self.field_position_vec_inner(inner_type_string.as_str(), fields, position_vec);
202            } else {
203                return self.field_position_vec_inner(field_type, fields, position_vec);
204            }
205        }
206        // }
207    }
208    // 将&str 转为定位的&str数组
209    pub fn to_local_vec(&self, local: &str, struct_name: &str) -> Result<Vec<String>, String> {
210        let string = local.replace("[", ".");
211        let string = string.as_str().replace("]", "."); // 可以优化
212        let mut vec:Vec<&str> = string.as_str().split(".").collect();
213        let mut string_vec = Vec::new();
214        for e in vec {
215            let e_s = String::from(e);
216            if e_s.len() == 0 {
217                continue;
218            }
219            string_vec.push(e_s);
220        }
221        string_vec.reverse();
222        string_vec.push(String::from(struct_name));
223        Ok(string_vec)
224    }
225    pub fn field_position(&self, fields:&mut Vec<String>) -> Result<Vec<usize>, String> {
226        // 先将 Vec<String> 转为 Vec<&str>
227        let mut vec:Vec<&str> = Vec::new();
228        for i in 0..fields.len() {
229            vec.push(fields[i].as_str());
230        }
231        self.field_position_vec(&mut vec)
232    }
233}