streaming_crypto/core_api/
utils.rs1use 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, }
36pub fn compute_checksum(data: &[u8], alg: Option<ChecksumAlg>) -> u32 {
37 match alg {
38 Some(ChecksumAlg::Crc32) => compute_crc32(data),
39 _ => 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
51static INIT: Once = Once::new();
59pub fn tracing_logger(_level: Option<Level>) {
62 INIT.call_once(|| {
63 let filter = EnvFilter::from_default_env(); let subscriber = tracing_subscriber::fmt()
68 .with_env_filter(filter)
69 .with_target(false) .with_thread_names(true) .finish();
73
74 tracing::subscriber::set_global_default(subscriber)
75 .expect("Failed to set global tracing subscriber");
76 });
77}
78
79