Krolyxon
Commit 83c5894

Branches

Refs →

budctlcratesbudctl-coresrcdebug.rs

42 lines · 1.0 KB · Rust

1//! `--debug` output on stderr: a hex dump of every byte sent and received, plus notes on what
2//! budctl decoded and decided. Off by default.
3
4use std::sync::atomic::{AtomicBool, Ordering};
5
6static ENABLED: AtomicBool = AtomicBool::new(false);
7
8pub fn enable() {
9 ENABLED.store(true, Ordering::Relaxed);
10}
11
12pub fn enabled() -> bool {
13 ENABLED.load(Ordering::Relaxed)
14}
15
16/// Print a note when debugging is on. The message is only built if it will be printed.
17pub(crate) fn note(message: impl FnOnce() -> String) {
18 if enabled() {
19 eprintln!("# {}", message());
20 }
21}
22
23/// `AA 07 00 …`
24pub fn hex(bytes: &[u8]) -> String {
25 let mut out = String::with_capacity(bytes.len() * 3);
26 for (i, byte) in bytes.iter().enumerate() {
27 if i > 0 {
28 out.push(' ');
29 }
30 out.push_str(&format!("{byte:02X}"));
31 }
32 out
33}
34
35#[cfg(test)]
36mod tests {
37 #[test]
38 fn hex_is_spaced_uppercase() {
39 assert_eq!(super::hex(&[0xAA, 0x07, 0x00]), "AA 07 00");
40 assert_eq!(super::hex(&[]), "");
41 }
42}