1+ use std:: num:: ParseIntError ;
2+ use anyhow:: { Result } ;
3+ use pretty_hex:: { HexConfig , PrettyHex } ;
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. hex_conf ( HexConfig {
29+ title : false ,
30+ ascii : false ,
31+ width : 0 ,
32+ group : 0 ,
33+ chunk : 0 ,
34+ max_bytes : usize:: MAX ,
35+ display_offset : 0 ,
36+ } ) . to_string ( ) )
37+ }
38+ }
39+
40+ impl SerializableContentview for HexStream {
41+ fn serialize ( & self , data : String ) -> Result < Vec < u8 > , SerializeError > {
42+ ( 0 ..data. len ( ) )
43+ . step_by ( 2 )
44+ . map ( |i| u8:: from_str_radix ( & data[ i..i + 2 ] , 16 ) )
45+ . collect :: < Result < Vec < u8 > , ParseIntError > > ( )
46+ . map_err (
47+ |e| SerializeError :: InvalidFormat ( format ! ( "Failed to parse hex string: {}" , e) ) )
48+ }
49+ }
50+
51+ #[ cfg( test) ]
52+ mod tests {
53+ use super :: * ;
54+
55+ #[ test]
56+ fn test_hexstream_deserialize ( ) {
57+ let hex_stream = HexStream :: default ( ) ;
58+ let data = b"foo" . to_vec ( ) ;
59+ let result = hex_stream. deserialize ( data) . unwrap ( ) ;
60+ assert_eq ! ( result, "666f6f" ) ;
61+ }
62+
63+ #[ test]
64+ fn test_hexstream_deserialize_empty ( ) {
65+ let hex_stream = HexStream :: default ( ) ;
66+ let data = vec ! [ ] ;
67+ let result = hex_stream. deserialize ( data) . unwrap ( ) ;
68+ assert_eq ! ( result, "" ) ;
69+ }
70+
71+ #[ test]
72+ fn test_hexstream_serialize ( ) {
73+ let hex_stream = HexStream :: default ( ) ;
74+ let data = "666f6f" . to_string ( ) ;
75+ let result = hex_stream. serialize ( data) . unwrap ( ) ;
76+ assert_eq ! ( result, b"foo" ) ;
77+ }
78+ }
0 commit comments