hotshot_new_protocol/
logging.rs1use std::{env, fmt, sync::Once};
2
3use hotshot::types::SignatureKey;
4use tracing_subscriber::EnvFilter;
5
6static LOG_INIT: Once = Once::new();
7
8pub fn init_logging() {
9 LOG_INIT.call_once(|| {
10 if env::var("RUST_LOG_FORMAT") == Ok("json".to_string()) {
11 tracing_subscriber::fmt()
12 .with_env_filter(EnvFilter::from_default_env())
13 .json()
14 .init();
15 } else {
16 tracing_subscriber::fmt()
17 .with_env_filter(EnvFilter::from_default_env())
18 .with_ansi(use_color())
19 .init();
20 }
21 });
22}
23
24pub fn init_test_logging() {
29 LOG_INIT.call_once(|| {
30 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("error"));
31 tracing_subscriber::fmt()
32 .with_env_filter(filter)
33 .with_ansi(use_color())
34 .with_test_writer()
35 .init();
36 });
37}
38
39fn use_color() -> bool {
40 env::var_os("NO_COLOR").is_none()
41}
42
43const KEY_PREFIX_LEN: usize = 19;
44
45#[derive(Clone, Copy)]
46pub struct KeyPrefix([u8; KEY_PREFIX_LEN]);
47
48impl<K: SignatureKey> From<&K> for KeyPrefix {
49 fn from(k: &K) -> Self {
50 let s = k.to_string();
51 let bytes = s.as_bytes();
52
53 let mut buf = [0u8; KEY_PREFIX_LEN];
54 let len = bytes.len().min(KEY_PREFIX_LEN);
55 buf[..len].copy_from_slice(&bytes[..len]);
56
57 Self(buf)
58 }
59}
60
61impl fmt::Display for KeyPrefix {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 let s = String::from_utf8_lossy(&self.0);
64 f.write_str(&s)
65 }
66}