Skip to content

Commit c2a5155

Browse files
Merge pull request #912 from multiversx/opcode-cost-deserialize-gen
opcodeCost deserialization generated code
2 parents 56769a1 + d569706 commit c2a5155

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

vmhost/vmhooks/generate/eiGenWriteRustOpcodeCost.go

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,57 @@ import (
77
"strings"
88
)
99

10+
const useStatements = `
11+
use serde::{Deserialize, Serialize};
12+
use std::fs;
13+
use std::path::Path;
14+
15+
use crate::GasSchedule;
16+
17+
`
18+
19+
const configStruct = `
20+
#[derive(Deserialize)]
21+
struct Config {
22+
#[serde(rename = "WASMOpcodeCost")]
23+
wasm_opcode_cost: OpcodeCost,
24+
}
25+
26+
`
27+
28+
const implBlock = `impl OpcodeCost {
29+
pub fn new(gas_schedule: GasSchedule) -> Self {
30+
let schedule_path = Path::new(env!("CARGO_MANIFEST_DIR"))
31+
.join("schedules")
32+
.join(gas_schedule.to_string());
33+
34+
Self::from_file(schedule_path).unwrap()
35+
}
36+
37+
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, std::io::Error> {
38+
let content = fs::read_to_string(path)?;
39+
Self::from_toml_str(&content)
40+
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))
41+
}
42+
43+
pub fn from_toml_str(content: &str) -> Result<Self, toml::de::Error> {
44+
let config: Config = toml::from_str(content)?;
45+
Ok(config.wasm_opcode_cost)
46+
}
47+
}
48+
`
49+
1050
// WriteRustOpcodeCost generates code for opcode_cost.rs
1151
func WriteRustOpcodeCost(out *eiGenWriter) {
1252
out.WriteString(`// Code generated by vmhooks generator. DO NOT EDIT.
1353
1454
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1555
// !!!!!!!!!!!!!!!!!!!!!! AUTO-GENERATED FILE !!!!!!!!!!!!!!!!!!!!!!
1656
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
17-
1857
`)
19-
out.WriteString("#[derive(Clone, Debug, Default)]\n")
58+
out.WriteString(useStatements)
59+
out.WriteString("#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]\n")
60+
out.WriteString("#[serde(default)]\n")
2061
out.WriteString("pub struct OpcodeCost {\n")
2162

2263
readFile, err := os.Open("generate/cmd/input/wasmer2_opcodes_short.txt")
@@ -30,7 +71,10 @@ func WriteRustOpcodeCost(out *eiGenWriter) {
3071

3172
for fileScanner.Scan() {
3273
line := fileScanner.Text()
74+
out.WriteString(fmt.Sprintf(" #[serde(rename = \"%s\", default)]\n", line))
3375
out.WriteString(fmt.Sprintf(" pub opcode_%s: u32,\n", strings.ToLower(line)))
3476
}
3577
out.WriteString("}\n")
78+
out.WriteString(configStruct)
79+
out.WriteString(implBlock)
3680
}

0 commit comments

Comments
 (0)