multiversx_sc_scenario/api/local_api_vh/
print_api_vh.rs

1use std::cell::RefCell;
2
3use multiversx_sc::{
4    api::{PrintApi, PrintApiImpl},
5    types::ManagedBufferBuilder,
6};
7
8use crate::api::{VMHooksApi, VMHooksApiBackend};
9
10thread_local!(
11    static PRINTED_MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) }
12);
13
14impl<VHB: VMHooksApiBackend> VMHooksApi<VHB> {
15    /// Clears static buffer used for testing.
16    pub fn printed_messages_clear() {
17        PRINTED_MESSAGES.with(|cell| cell.replace(Vec::new()));
18    }
19
20    /// Whenever using `sc_print!`, the message gets printed to console, but also gets saved in a static buffer, for testing.
21    ///
22    /// This method retrieves a copy of the contents of that static print message buffer.
23    pub fn printed_messages() -> Vec<String> {
24        PRINTED_MESSAGES.with(|cell| cell.borrow().clone())
25    }
26}
27
28impl<VHB: VMHooksApiBackend> PrintApi for VMHooksApi<VHB> {
29    type PrintApiImpl = Self;
30
31    fn print_api_impl() -> Self::PrintApiImpl {
32        Self::api_impl()
33    }
34}
35
36impl<VHB: VMHooksApiBackend> PrintApiImpl for VMHooksApi<VHB> {
37    type Buffer = ManagedBufferBuilder<Self>;
38
39    fn print_buffer(&self, buffer: Self::Buffer) {
40        let bytes = buffer.into_managed_buffer().to_boxed_bytes();
41        let s = String::from_utf8_lossy(bytes.as_slice());
42        println!("{:?}", &s);
43        PRINTED_MESSAGES.with(|cell| cell.borrow_mut().push(s.into_owned()));
44    }
45}