Skip to main content

solana_msg/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#[cfg(feature = "alloc")]
4extern crate alloc;
5#[cfg(feature = "std")]
6extern crate std;
7
8/// We re-export the `format!` macro from `alloc` for use in the `msg!` macro
9#[cfg(feature = "alloc")]
10#[doc(hidden)]
11pub use alloc::format;
12
13/// Print a message to the log.
14///
15/// Supports simple strings as well as Rust [format strings][fs]. When passed a
16/// single expression it will be passed directly to [`sol_log`]. The expression
17/// must have type `&str`, and is typically used for logging static strings.
18/// When passed something other than an expression, particularly
19/// a sequence of expressions, the tokens will be passed through the
20/// [`format!`] macro before being logged with `sol_log`.
21///
22/// [fs]: https://doc.rust-lang.org/alloc/fmt/
23/// [`format!`]: https://doc.rust-lang.org/alloc/fmt/fn.format.html
24///
25/// Note that Rust's formatting machinery is relatively CPU-intensive
26/// for constrained environments like the Solana VM.
27///
28/// # Examples
29///
30/// ```
31/// use solana_msg::msg;
32///
33/// // The fast form
34/// msg!("verifying multisig");
35///
36/// // With formatting
37/// let err = "not enough signers";
38/// msg!("multisig failed: {}", err);
39/// ```
40#[cfg(feature = "alloc")]
41#[macro_export]
42macro_rules! msg {
43    ($msg:expr) => {
44        $crate::sol_log($msg)
45    };
46    ($($arg:tt)*) => ($crate::sol_log(&$crate::format!($($arg)*)));
47}
48
49#[cfg(target_os = "solana")]
50pub mod syscalls;
51
52/// Print a string to the log.
53#[inline]
54pub fn sol_log(message: &str) {
55    #[cfg(target_os = "solana")]
56    unsafe {
57        syscalls::sol_log_(message.as_ptr(), message.len() as u64);
58    }
59
60    #[cfg(all(not(target_os = "solana"), feature = "std"))]
61    std::println!("{message}");
62
63    #[cfg(all(not(target_os = "solana"), not(feature = "std")))]
64    core::hint::black_box(message);
65}