use encoding_rs::*;
pub fn convert_byte_array_to_string(data: &[u8]) -> String {
if data.is_empty() {
return String::new();
}
let effective = match data.iter().position(|&b| b == 0) {
Some(pos) => &data[..pos],
None => data,
};
if effective.is_empty() {
return String::new();
}
if let Ok(s) = std::str::from_utf8(effective) {
let trimmed = s.trim_matches(|c: char| c.is_control() && c != ' ');
if !trimmed.is_empty() && trimmed.chars().all(|c| !c.is_control() || c == ' ') {
return trimmed.to_string();
}
}
let (decoded, _, had_errors) = GBK.decode(effective);
if !had_errors {
let trimmed = decoded.trim_matches(|c: char| c.is_control() && c != ' ');
if !trimmed.is_empty() {
return trimmed.to_string();
}
}
if effective.len() >= 2 && effective.len() % 2 == 0 {
let (decoded, _, had_errors) = UTF_16LE.decode(effective);
if !had_errors {
let trimmed = decoded.trim_matches(|c: char| c.is_control() && c != ' ');
if !trimmed.is_empty()
&& trimmed
.chars()
.all(|c| c.is_ascii_graphic() || c.is_alphanumeric() || c == ' ')
{
return trimmed.to_string();
}
}
}
let ascii: String = effective
.iter()
.filter(|&&b| b >= 0x20 && b <= 0x7E)
.map(|&b| b as char)
.collect();
ascii
}
pub fn convert_fixed_name_to_string(bytes: &[u8; 41]) -> String {
convert_byte_array_to_string(bytes)
}
pub fn bytes_to_hex_display(data: &[u8]) -> String {
data.iter()
.map(|b| format!("{:02X}", b))
.collect::<Vec<_>>()
.join(" ")
}
pub fn ip_to_string(ip: &[u8; 4]) -> String {
format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3])
}