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
82
83
84
85
use super::*;
use std::str;
use nom::combinator::rest;
const MAX_ACTION_MESSAGE_DATA_SIZE: usize = 1372;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Action {
msg: String,
}
impl FromBytes for Action {
named!(from_bytes<Action>, do_parse!(
tag!("\x41") >>
msg: map_res!(verify!(rest, |msg: &[u8]| msg.len() <= MAX_ACTION_MESSAGE_DATA_SIZE),
str::from_utf8) >>
(Action { msg: msg.to_string() })
));
}
impl ToBytes for Action {
fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
do_gen!(buf,
gen_be_u8!(0x41) >>
gen_cond!(self.msg.len() > MAX_ACTION_MESSAGE_DATA_SIZE, |buf| gen_error(buf, 0)) >>
gen_slice!(self.msg.as_bytes())
)
}
}
impl Action {
pub fn new(msg: String) -> Self {
Action { msg }
}
}
#[cfg(test)]
mod tests {
use super::*;
encode_decode_test!(
tox_crypto::crypto_init().unwrap(),
action_encode_decode,
Action::new("1234".to_string())
);
#[test]
fn action_from_bytes_encoding_error() {
let err_string = vec![0, 159, 146, 150];
assert!(Action::from_bytes(&err_string).is_err());
}
#[test]
fn action_from_bytes_overflow() {
let large_string = vec![32; MAX_ACTION_MESSAGE_DATA_SIZE + 1];
assert!(Action::from_bytes(&large_string).is_err());
}
#[test]
fn action_to_bytes_overflow() {
let large_string = String::from_utf8(vec![32u8; MAX_ACTION_MESSAGE_DATA_SIZE + 1]).unwrap();
let large_msg = Action::new(large_string);
let mut buf = [0; MAX_ACTION_MESSAGE_DATA_SIZE + 1];
assert!(large_msg.to_bytes((&mut buf, 0)).is_err());
}
}