1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
pub use crate::types::*;
pub use std::ffi::CString;
pub use std::fmt;
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Variable {
pub name: String,
pub var_type: Box<VariableType>,
pub kind: FileType,
}
impl Variable {
pub fn new(name: &str, var_type: VariableType, kind: FileType) -> Self {
Self {
name: String::from(name),
var_type: Box::new(var_type),
kind,
}
}
pub fn is_pointer(self) -> bool {
match *self.var_type {
VariableType::UCharPtr(_, _) | VariableType::Str(_) | VariableType::VoidPtr => true,
_ => false,
}
}
}
impl fmt::Display for Variable {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &*self.var_type {
VariableType::Long(value) => write!(f, "\tlong {} = {};\n", self.name, value),
VariableType::Str(value) => {
let cstr = format!(
"{:?}",
CString::new(&**value).expect("invalid c string in fmt::Display Variable")
);
let mut var = String::from(&cstr[1..cstr.len() - 1]);
var.push_str("\\x00");
write!(f, "\tchar {}[] = \"{}\";\n", self.name, var)
}
VariableType::UCharPtr(value, size) => {
let mut line = format!("\tunsigned char {}[{}];\n", self.name, size);
match value {
None => {
line.push_str(&format!("\tmemset({}, 0,", self.name));
line.push_str(&format!("{});\n", size));
}
Some(v) => {
line.push_str(&format!(
"\tmemcpy({},{:?}",
self.name,
CString::new(&*v.clone())
.expect("invalid c string in fmt::Display Veriable UCharPtr")
));
line.push_str(&format!(",{});", size));
}
}
return write!(f, "{}", line);
}
_ => Err(fmt::Error),
}
}
}