pallet_revive_fixtures/
lib.rs1#![cfg_attr(not(feature = "std"), no_std)]
19
20extern crate alloc;
21
22include!(concat!(env!("OUT_DIR"), "/fixture_location.rs"));
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum FixtureType {
28 Rust,
30 Resolc,
32 Solc,
34}
35
36#[cfg(feature = "std")]
37impl FixtureType {
38 fn file_extension(&self) -> &'static str {
39 match self {
40 Self::Rust => ".polkavm",
41 Self::Resolc => ".resolc.polkavm",
42 Self::Solc => ".sol.bin",
43 }
44 }
45}
46
47#[cfg(feature = "std")]
49pub fn compile_module_with_type(
50 fixture_name: &str,
51 fixture_type: FixtureType,
52) -> anyhow::Result<(Vec<u8>, sp_core::H256)> {
53 use anyhow::Context;
54 let out_dir: std::path::PathBuf = FIXTURE_DIR.into();
55 let fixture_path = out_dir.join(format!("{fixture_name}{}", fixture_type.file_extension()));
56 let binary = std::fs::read(&fixture_path)
57 .with_context(|| format!("Failed to load fixture {fixture_path:?}"))?;
58 let code_hash = sp_io::hashing::keccak_256(&binary);
59 Ok((binary, sp_core::H256(code_hash)))
60}
61
62#[cfg(feature = "std")]
64pub fn compile_module(fixture_name: &str) -> anyhow::Result<(Vec<u8>, sp_core::H256)> {
65 compile_module_with_type(fixture_name, FixtureType::Rust)
66}
67
68pub mod bench {
73 use alloc::vec::Vec;
74 pub const DUMMY: Option<&[u8]> = fixture!("dummy");
75 pub const NOOP: Option<&[u8]> = fixture!("noop");
76
77 pub fn dummy() -> &'static [u8] {
78 DUMMY.expect("`DUMMY` fixture not available, remove `SKIP_PALLET_REVIVE_FIXTURES` env variable to compile them.")
79 }
80
81 pub fn noop() -> &'static [u8] {
82 NOOP.expect("`NOOP` fixture not available, remove `SKIP_PALLET_REVIVE_FIXTURES` env variable to compile them.")
83 }
84
85 pub fn dummy_unique(replace_with: u32) -> Vec<u8> {
86 let mut dummy = dummy().to_vec();
87 let idx = dummy
88 .windows(4)
89 .position(|w| w == &[0xDE, 0xAD, 0xBE, 0xEF])
90 .expect("Benchmark fixture contains this pattern; qed");
91 dummy[idx..idx + 4].copy_from_slice(&replace_with.to_le_bytes());
92 dummy
93 }
94}
95
96#[cfg(test)]
97mod test {
98 #[test]
99 fn out_dir_should_have_compiled_mocks() {
100 let out_dir: std::path::PathBuf = crate::FIXTURE_DIR.into();
101 assert!(out_dir.join("dummy.polkavm").exists());
102 }
103}