Skip to main content

xmtp_common/
fmt.rs

1/// print bytes as a truncated hex string
2pub fn debug_hex(bytes: impl AsRef<[u8]>) -> String {
3    truncate_hex(hex::encode(bytes.as_ref()))
4}
5
6pub fn truncate_hex(hex_string: impl AsRef<str>) -> String {
7    let hex_string = hex_string.as_ref();
8    // If empty string, return it
9    if hex_string.is_empty() {
10        return String::new();
11    }
12
13    let hex_value = if let Some(hex_value) = hex_string.strip_prefix("0x") {
14        hex_value
15    } else {
16        hex_string
17    };
18
19    // If the hex value is 8 or fewer chars, return original string
20    if hex_value.len() <= 8 {
21        return hex_string.to_string();
22    }
23
24    format!(
25        "0x{}...{}",
26        &hex_value[..4],
27        &hex_value[hex_value.len() - 4..]
28    )
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn test_long_hex() {
37        assert_eq!(
38            truncate_hex("0x5bf078bd83995fe83092d93c5655f059"),
39            "0x5bf0...f059"
40        );
41    }
42}