1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use std::io::{Error, ErrorKind, Result};
use log::debug;
use crate::message::{self, compress, Compressor};
impl Compressor for message::put::Message {
fn compress_with_header(&self) -> Result<bytes::Bytes> {
let type_id = message::TYPES
.get("put")
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, "unknown type name"))?;
let packer = message::default_packer();
packer.pack_bytes(self.chain_id.as_ref())?;
packer.pack_u32(self.request_id)?;
packer.pack_bytes(self.container_id.as_ref())?;
packer.pack_bytes_with_header(self.container_bytes.as_ref())?;
let bytes_uncompressed = packer.bytes_len();
let compressed = compress::pack_gzip(&packer.take_bytes())?;
let bytes_compressed = compressed.len();
let packer = message::default_packer_with_header();
packer.pack_byte(*type_id)?;
packer.pack_bool(true)?;
packer.pack_bytes(compressed.as_ref())?;
if bytes_uncompressed > bytes_compressed {
debug!(
"put compression saved {} bytes",
bytes_uncompressed - bytes_compressed
);
} else {
debug!(
"put compression added {} byte(s)",
bytes_compressed - bytes_uncompressed
);
}
Ok(packer.take_bytes())
}
}
#[test]
fn test_message() {
use crate::ids;
use avalanche_utils::cmp;
let msg = message::put::Message::create(
ids::Id::empty(),
7,
ids::Id::from_slice(&[
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x01,
]),
vec![0x01, 0x02, 0x03],
);
let data_with_header = msg.compress_with_header().unwrap();
let expected_data: &[u8] = &[
0x00, 0x00, 0x00, 0x2d,
0x0d,
0x01,
0x1f, 0x8b, 0x8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x85, 0xc9, 0xb1, 0x1, 0x0, 0x0, 0x8,
0xc2, 0x30, 0x2a, 0x83, 0xff, 0x7f, 0xac, 0x17, 0x40, 0x87, 0x2e, 0x91, 0x6a, 0x9b, 0x19,
0x7e, 0x66, 0x7c, 0x47, 0xe6, 0x86, 0x7b, 0x4b, 0x0, 0x0, 0x0,
];
assert!(cmp::eq_vectors(expected_data, &data_with_header));
}