From bd9e6e970e04ea9d84ccba284e4aad19a4d5471f Mon Sep 17 00:00:00 2001 From: Shamil <66209982+shamilsan@users.noreply.github.com> Date: Wed, 20 Dec 2023 20:30:31 +0300 Subject: [PATCH] feat(gstd): add the missing `dbg!` macro (#3610) --- gstd/src/macros/debug.rs | 36 ++++++++++++++++++++++++++++++++++++ gstd/src/prelude.rs | 1 + gstd/tests/debug.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 gstd/tests/debug.rs diff --git a/gstd/src/macros/debug.rs b/gstd/src/macros/debug.rs index 2d41395c6fa..19eb339b64f 100644 --- a/gstd/src/macros/debug.rs +++ b/gstd/src/macros/debug.rs @@ -59,3 +59,39 @@ macro_rules! debug { macro_rules! debug { ($($arg:tt)*) => {}; } + +/// Prints and returns the value of a given expression for quick and dirty +/// debugging. +/// +/// Similar to the standard library's +/// [`dbg!`](https://doc.rust-lang.org/std/macro.dbg.html) macro. +#[cfg(any(feature = "debug", debug_assertions))] +#[macro_export] +macro_rules! dbg { + () => { + $crate::debug!("[{}:{}]", $crate::prelude::file!(), $crate::prelude::line!()) + }; + ($val:expr $(,)?) => { + match $val { + tmp => { + $crate::debug!("[{}:{}] {} = {:#?}", + $crate::prelude::file!(), + $crate::prelude::line!(), + $crate::prelude::stringify!($val), + &tmp, + ); + tmp + } + } + }; + ($($val:expr),+ $(,)?) => { + ($($crate::dbg!($val)),+,) + }; +} + +#[cfg(not(any(feature = "debug", debug_assertions)))] +#[allow(missing_docs)] +#[macro_export] +macro_rules! dbg { + ($($arg:tt)*) => {}; +} diff --git a/gstd/src/prelude.rs b/gstd/src/prelude.rs index f8dc00ba690..7da3ec86773 100644 --- a/gstd/src/prelude.rs +++ b/gstd/src/prelude.rs @@ -21,6 +21,7 @@ // Reexports from Rust's libraries +pub use crate::dbg; pub use ::alloc::{ borrow, borrow::ToOwned, diff --git a/gstd/tests/debug.rs b/gstd/tests/debug.rs new file mode 100644 index 00000000000..f01eeda4eab --- /dev/null +++ b/gstd/tests/debug.rs @@ -0,0 +1,33 @@ +use gstd::{debug, prelude::*}; + +static mut DEBUG_MSG: Vec = Vec::new(); + +mod sys { + use super::*; + + #[no_mangle] + unsafe extern "C" fn gr_debug(payload: *const u8, len: u32) { + DEBUG_MSG.resize(len as _, 0); + ptr::copy(payload, DEBUG_MSG.as_mut_ptr(), len as _); + } +} + +#[test] +fn test_debug() { + let value = 42; + + debug!("{value}"); + assert_eq!(unsafe { &DEBUG_MSG }, b"42"); + + debug!("Formatted: value = {value}"); + assert_eq!(unsafe { &DEBUG_MSG }, b"Formatted: value = 42"); + + debug!("String literal"); + assert_eq!(unsafe { &DEBUG_MSG }, b"String literal"); + + crate::dbg!(value); + assert_eq!( + unsafe { &DEBUG_MSG }, + b"[gstd/tests/debug.rs:28] value = 42" + ); +}