87 lines
2.5 KiB
Rust
87 lines
2.5 KiB
Rust
use byteorder::WriteBytesExt;
|
|
use num_bigint::{BigInt, BigUint};
|
|
use serde::Deserialize;
|
|
|
|
use crate::formatter::format::ByteOrderOperations;
|
|
|
|
pub fn print_bytes_as_array(data: &[u8]) -> String {
|
|
format!("{:?}", data)
|
|
}
|
|
|
|
pub fn base_notation(b: u32) -> String {
|
|
match b {
|
|
2 => "0b".to_string(),
|
|
8 => "0".to_string(),
|
|
10 => "".to_string(),
|
|
16 => "0x".to_string(),
|
|
_ => format!("Base({}) ", b),
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Deserialize, Clone, Default)]
|
|
#[serde(tag = "print")]
|
|
pub enum PrintType {
|
|
Base { base: u32 },
|
|
ByteArray,
|
|
String,
|
|
#[default]
|
|
Default,
|
|
}
|
|
impl PrintType {
|
|
pub fn print_big_int<T: ByteOrderOperations>(&self, big_int: BigInt) -> String {
|
|
match self {
|
|
PrintType::Base { base: b } => {
|
|
format!("{}{}", base_notation(*b), big_int.to_str_radix(*b))
|
|
}
|
|
PrintType::ByteArray => print_bytes_as_array(&T::big_int_to_bytes(big_int)),
|
|
_ => big_int.to_string(),
|
|
}
|
|
}
|
|
|
|
pub fn print_big_u_int<T: ByteOrderOperations>(&self, big_int: BigUint) -> String {
|
|
match self {
|
|
PrintType::Base { base: b } => {
|
|
format!("{}{}", base_notation(*b), big_int.to_str_radix(*b))
|
|
}
|
|
PrintType::ByteArray => print_bytes_as_array(&T::big_u_int_to_bytes(big_int)),
|
|
_ => big_int.to_string(),
|
|
}
|
|
}
|
|
|
|
pub fn print_float<T: ByteOrderOperations>(&self, float: f32) -> String {
|
|
match self {
|
|
PrintType::ByteArray => {
|
|
let mut bytes = Vec::with_capacity(4);
|
|
bytes.write_f32::<T>(float).unwrap();
|
|
print_bytes_as_array(&bytes)
|
|
}
|
|
_ => float.to_string(),
|
|
}
|
|
}
|
|
|
|
pub fn print_double<T: ByteOrderOperations>(&self, double: f64) -> String {
|
|
match self {
|
|
PrintType::ByteArray => {
|
|
let mut bytes = Vec::with_capacity(8);
|
|
bytes.write_f64::<T>(double).unwrap();
|
|
print_bytes_as_array(&bytes)
|
|
}
|
|
_ => double.to_string(),
|
|
}
|
|
}
|
|
|
|
pub fn print_bytes(&self, bytes: &[u8]) -> String {
|
|
match self {
|
|
PrintType::String => std::str::from_utf8(bytes).unwrap().to_string(),
|
|
_ => print_bytes_as_array(bytes)
|
|
}
|
|
}
|
|
|
|
pub fn print_string(&self, s: &str) -> String {
|
|
match self {
|
|
PrintType::ByteArray => print_bytes_as_array(s.as_bytes()),
|
|
_ => s.to_string(),
|
|
}
|
|
}
|
|
}
|