Cactus/net/packet/
utils.rs

1//! This module exposes some utility functions, mainly for creating visual things.
2
3use std::any::{type_name, type_name_of_val};
4
5/// Returns the hexadecimal representation of bytes.
6/// E.g., 65535 -> 0xFF 0xFF
7pub fn get_hex_repr(data: &[u8]) -> String {
8    data.iter()
9        .map(|b| format!("{:02X}", b))
10        .collect::<Vec<String>>()
11        .join(" ")
12}
13
14/// Returns the binary representation of bytes.
15/// E.g., 65535 -> 11111111 11111111
16pub fn get_bin_repr(data: &[u8]) -> String {
17    data.iter()
18        .map(|b| format!("{:08b}", b))
19        .collect::<Vec<String>>()
20        .join(" ")
21}
22
23/// Returns the decimal representation of bytes.
24pub fn get_dec_repr(data: &[u8]) -> String {
25    data.iter()
26        .map(|b| format!("{}", b))
27        .collect::<Vec<String>>()
28        .join(" ")
29}
30
31/// Returns the name of a type as a string slice,
32/// or the name of the type of value.
33pub fn name_of<T>(value: Option<&T>) -> &'static str {
34    match value {
35        None => type_name::<T>().rsplit("::").next().unwrap(),
36        Some(v) => type_name_of_val(v).rsplit("::").next().unwrap(),
37    }
38}