|
| 1 | +use anyhow::Result; |
| 2 | +use pretty_hex::{HexConfig, PrettyHex}; |
| 3 | +use std::num::ParseIntError; |
| 4 | + |
| 5 | +#[derive(Debug)] |
| 6 | +pub enum SerializeError { |
| 7 | + InvalidFormat(String), |
| 8 | +} |
| 9 | + |
| 10 | +pub trait Contentview: Send + Sync { |
| 11 | + fn name(&self) -> &str; |
| 12 | + fn deserialize(&self, data: Vec<u8>) -> Result<String>; |
| 13 | +} |
| 14 | + |
| 15 | +pub trait SerializableContentview: Contentview { |
| 16 | + fn serialize(&self, data: String) -> Result<Vec<u8>, SerializeError>; |
| 17 | +} |
| 18 | + |
| 19 | +#[derive(Default)] |
| 20 | +pub struct HexStream(); |
| 21 | + |
| 22 | +impl Contentview for HexStream { |
| 23 | + fn name(&self) -> &str { |
| 24 | + "HexStream" |
| 25 | + } |
| 26 | + |
| 27 | + fn deserialize(&self, data: Vec<u8>) -> Result<String> { |
| 28 | + Ok(data |
| 29 | + .hex_conf(HexConfig { |
| 30 | + title: false, |
| 31 | + ascii: false, |
| 32 | + width: 0, |
| 33 | + group: 0, |
| 34 | + chunk: 0, |
| 35 | + max_bytes: usize::MAX, |
| 36 | + display_offset: 0, |
| 37 | + }) |
| 38 | + .to_string()) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +impl SerializableContentview for HexStream { |
| 43 | + fn serialize(&self, data: String) -> Result<Vec<u8>, SerializeError> { |
| 44 | + (0..data.len()) |
| 45 | + .step_by(2) |
| 46 | + .map(|i| u8::from_str_radix(&data[i..i + 2], 16)) |
| 47 | + .collect::<Result<Vec<u8>, ParseIntError>>() |
| 48 | + .map_err(|e| { |
| 49 | + SerializeError::InvalidFormat(format!("Failed to parse hex string: {}", e)) |
| 50 | + }) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +#[cfg(test)] |
| 55 | +mod tests { |
| 56 | + use super::*; |
| 57 | + |
| 58 | + #[test] |
| 59 | + fn test_hexstream_deserialize() { |
| 60 | + let hex_stream = HexStream::default(); |
| 61 | + let data = b"foo".to_vec(); |
| 62 | + let result = hex_stream.deserialize(data).unwrap(); |
| 63 | + assert_eq!(result, "666f6f"); |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_hexstream_deserialize_empty() { |
| 68 | + let hex_stream = HexStream::default(); |
| 69 | + let data = vec![]; |
| 70 | + let result = hex_stream.deserialize(data).unwrap(); |
| 71 | + assert_eq!(result, ""); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn test_hexstream_serialize() { |
| 76 | + let hex_stream = HexStream::default(); |
| 77 | + let data = "666f6f".to_string(); |
| 78 | + let result = hex_stream.serialize(data).unwrap(); |
| 79 | + assert_eq!(result, b"foo"); |
| 80 | + } |
| 81 | +} |
0 commit comments