near_primitives_core_v01/
logging.rs

1use std::fmt::Debug;
2
3use crate::serialize::to_base;
4
5const VECTOR_MAX_LENGTH: usize = 5;
6const STRING_PRINT_LEN: usize = 128;
7
8pub fn pretty_vec<T: Debug>(buf: &[T]) -> String {
9    if buf.len() <= VECTOR_MAX_LENGTH {
10        format!("{:#?}", buf)
11    } else {
12        format!(
13            "({})[{:#?}, {:#?}, … {:#?}, {:#?}]",
14            buf.len(),
15            buf[0],
16            buf[1],
17            buf[buf.len() - 2],
18            buf[buf.len() - 1]
19        )
20    }
21}
22
23pub fn pretty_str(s: &str, print_len: usize) -> String {
24    if s.len() <= print_len {
25        format!("`{}`", s)
26    } else {
27        format!("({})`{}…`", s.len(), &s.chars().take(print_len).collect::<String>())
28    }
29}
30
31pub fn pretty_hash(s: &str) -> String {
32    pretty_str(s, STRING_PRINT_LEN)
33}
34
35pub fn pretty_utf8(buf: &[u8]) -> String {
36    match std::str::from_utf8(buf) {
37        Ok(s) => pretty_hash(s),
38        Err(_) => {
39            if buf.len() <= STRING_PRINT_LEN {
40                pretty_hash(&to_base(buf))
41            } else {
42                pretty_vec(buf)
43            }
44        }
45    }
46}
47
48pub fn pretty_result(result: &Option<Vec<u8>>) -> String {
49    match result {
50        Some(ref v) => pretty_utf8(&v),
51        None => "None".to_string(),
52    }
53}
54
55pub fn pretty_results(results: &[Option<Vec<u8>>]) -> String {
56    let v: Vec<String> = results.iter().map(pretty_result).collect();
57    format!("{:?}", pretty_vec(&v))
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    static HI_NEAR: &str = "Привет, NEAR";
65
66    #[test]
67    fn test_non_ut8_string_truncation() {
68        assert_eq!(format!("({})`Привет…`", HI_NEAR.len()), pretty_str(HI_NEAR, 6));
69    }
70
71    #[test]
72    fn test_non_ut8_more_bytes_same_char_count() {
73        assert_eq!(
74            format!("({})`{}…`", HI_NEAR.len(), HI_NEAR),
75            pretty_str(HI_NEAR, HI_NEAR.chars().count())
76        );
77    }
78
79    #[test]
80    fn test_non_ut8_no_truncation() {
81        assert_eq!(format!("`{}`", HI_NEAR), pretty_str(HI_NEAR, HI_NEAR.len()));
82    }
83}