Skip to content

Commit

Permalink
feat(gstd): add the missing dbg! macro (#3610)
Browse files Browse the repository at this point in the history
  • Loading branch information
shamilsan authored Dec 20, 2023
1 parent cb31d73 commit bd9e6e9
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
36 changes: 36 additions & 0 deletions gstd/src/macros/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)*) => {};
}
1 change: 1 addition & 0 deletions gstd/src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

// Reexports from Rust's libraries

pub use crate::dbg;
pub use ::alloc::{
borrow,
borrow::ToOwned,
Expand Down
33 changes: 33 additions & 0 deletions gstd/tests/debug.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use gstd::{debug, prelude::*};

static mut DEBUG_MSG: Vec<u8> = 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"
);
}

0 comments on commit bd9e6e9

Please sign in to comment.