-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_modifier_with2.rs
47 lines (34 loc) · 1.39 KB
/
test_modifier_with2.rs
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
use jbytes_derive::{ByteEncode, ByteDecode};
use jbytes::prelude::*;
/// This is just a demonstration, so go straight back.
fn custom_with_decode<I: BufRead>(input: &I, _cattr: Option<&ContainerAttrModifiers>, _fattr: Option<&FieldAttrModifiers>) -> JResult<WithExample> {
let key = match input.take_bytes(3)? {
b"get" => 1,
b"put" => 2,
_ => return Err(make_error(input.get_position(), ErrorKind::Fail)),
};
let value = input.take_u32()?;
Ok(WithExample {key, value})
}
fn custom_with_encode<B: BufWrite>(buffer: &mut B, _cattr: Option<&ContainerAttrModifiers>, _fattr: Option<&FieldAttrModifiers>, value: &WithExample) -> JResult<usize> {
let mut r_nbytes = match value.key {
1 => buffer.push_bytes(b"get")?,
2 => buffer.push_bytes(b"put")?,
_ => 0,
};
r_nbytes += buffer.push_u32(value.value)?;
Ok(r_nbytes)
}
#[derive(Debug, PartialEq, Eq, ByteEncode, ByteDecode)]
#[jbytes(decode_with="custom_with_decode", encode_with="custom_with_encode")]
pub struct WithExample {
pub key: u8,
pub value: u32,
}
#[test]
fn test_modifier_with() {
let bytes = Bytes::new(b"get\x00\x00\x00\x01");
assert_eq!(WithExample::decode(&bytes).unwrap(), WithExample { key: 1, value: 1 });
assert_eq!(bytes.remaining_len(), 0);
assert_eq!(*jbytes::encode(WithExample { key: 1, value: 1 }).unwrap(), b"get\x00\x00\x00\x01");
}