Skip to main content

streaming_crypto/core_api/
utils.rs

1use std::fmt;
2use std::sync::Once;
3use num_enum::TryFromPrimitive;
4use tracing::Level;
5use tracing_subscriber::EnvFilter;
6
7pub fn enum_name_or_hex<T>(raw: T::Primitive) -> String
8where
9    T: TryFromPrimitive + fmt::Debug,
10    T::Primitive: fmt::LowerHex,
11{
12    match T::try_from_primitive(raw) {
13        Ok(variant) => format!("{:?}", variant),
14        Err(_) => format!("0x{:x}", raw),
15    }
16}
17
18pub fn fmt_bytes(b: &[u8]) -> String {
19    if b.iter().all(|&c| c.is_ascii_graphic() || c == b' ') {
20        format!("b\"{}\"", String::from_utf8_lossy(b))
21    } else {
22        format!("0x{}", hex::encode(b))
23    }
24}
25
26pub fn to_hex(bytes: &[u8]) -> String {
27    bytes.iter().map(|b| format!("{:02x}", b)).collect::<String>()
28}
29
30#[repr(u16)]
31#[derive(Copy, Clone, Debug, PartialEq, Eq, TryFromPrimitive)]
32pub enum ChecksumAlg {
33    Crc32    = 0x0001,
34    Blake3   = 0x0201, // UN-KEYED Blake3
35}
36pub fn compute_checksum(data: &[u8], alg: Option<ChecksumAlg>) -> u32 {
37    match alg {
38        Some(ChecksumAlg::Crc32)  => compute_crc32(data),
39        // Some(ChecksumAlg::Blake3) => compute_blake3(data), // Its return 32-bytes
40        _                         => compute_crc32(data)
41    }
42}
43
44fn compute_crc32(data: &[u8]) -> u32 {
45    use crc32fast::Hasher;
46    let mut hasher = Hasher::new();
47    hasher.update(data);
48    hasher.finalize()
49}
50
51// fn compute_blake3(data: &[u8]) -> [u8; 32] {
52//     use blake3::Hasher;
53//     let mut hasher = Hasher::new();
54//     hasher.update(data);
55//     *hasher.finalize().as_bytes()
56// }
57
58static INIT: Once = Once::new();
59/// Initialize a default tracing logger with optional level.
60/// Call this once at the start of our program or benchmark.
61pub fn tracing_logger(_level: Option<Level>) {
62    INIT.call_once(|| {
63        // Build filter from RUST_LOG or fallback to provided level 
64        let filter = EnvFilter::from_default_env(); // respects RUST_LOG
65            // .add_directive(level.unwrap_or(Level::INFO).into());
66
67        let subscriber = tracing_subscriber::fmt()
68            .with_env_filter(filter)
69            // .with_max_level(level.unwrap_or(Level::INFO)) // default to INFO if None
70            .with_target(false)            // hide module path
71            .with_thread_names(true)       // show thread names
72            .finish();
73
74        tracing::subscriber::set_global_default(subscriber)
75            .expect("Failed to set global tracing subscriber");
76    });
77}
78
79// ```rust
80// fn main() {
81//     // Default INFO level
82//     tracing_logger(None);
83
84//     // Or explicitly set DEBUG level
85//     tracing_logger(Some(tracing::Level::DEBUG));
86
87//     tracing::info!("Benchmark starting");
88//     tracing::debug!("Debug details: {:?}", 42);
89// }
90// ```
91
92// ### 🔑 Notes
93// - `tracing_logger(None)` → defaults to `INFO`.  
94// - `tracing_logger(Some(Level::DEBUG))` → enables debug output.  
95// - We can still override with environment variables (`RUST_LOG=error cargo bench`) if we add `.with_env_filter(...)` to the subscriber.