/src/suricata7/rust/src/applayertemplate/parser.rs
Line | Count | Source |
1 | | /* Copyright (C) 2018 Open Information Security Foundation |
2 | | * |
3 | | * You can copy, redistribute or modify this Program under the terms of |
4 | | * the GNU General Public License version 2 as published by the Free |
5 | | * Software Foundation. |
6 | | * |
7 | | * This program is distributed in the hope that it will be useful, |
8 | | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
9 | | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
10 | | * GNU General Public License for more details. |
11 | | * |
12 | | * You should have received a copy of the GNU General Public License |
13 | | * version 2 along with this program; if not, write to the Free Software |
14 | | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
15 | | * 02110-1301, USA. |
16 | | */ |
17 | | |
18 | | use nom7::{ |
19 | | bytes::streaming::{take, take_until}, |
20 | | combinator::map_res, |
21 | | IResult, |
22 | | }; |
23 | | use std; |
24 | | |
25 | 211k | fn parse_len(input: &str) -> Result<u32, std::num::ParseIntError> { |
26 | 211k | input.parse::<u32>() |
27 | 211k | } |
28 | | |
29 | 217k | pub fn parse_message(i: &[u8]) -> IResult<&[u8], String> { |
30 | 217k | let (i, len) = map_res(map_res(take_until(":"), std::str::from_utf8), parse_len)(i)?; |
31 | 211k | let (i, _sep) = take(1_usize)(i)?; |
32 | 211k | let (i, msg) = map_res(take(len as usize), std::str::from_utf8)(i)?; |
33 | 153k | let result = msg.to_string(); |
34 | 153k | Ok((i, result)) |
35 | 217k | } |
36 | | |
37 | | #[cfg(test)] |
38 | | mod tests { |
39 | | use super::*; |
40 | | use nom7::Err; |
41 | | |
42 | | /// Simple test of some valid data. |
43 | | #[test] |
44 | | fn test_parse_valid() { |
45 | | let buf = b"12:Hello World!4:Bye."; |
46 | | |
47 | | let result = parse_message(buf); |
48 | | match result { |
49 | | Ok((remainder, message)) => { |
50 | | // Check the first message. |
51 | | assert_eq!(message, "Hello World!"); |
52 | | |
53 | | // And we should have 6 bytes left. |
54 | | assert_eq!(remainder.len(), 6); |
55 | | } |
56 | | Err(Err::Incomplete(_)) => { |
57 | | panic!("Result should not have been incomplete."); |
58 | | } |
59 | | Err(Err::Error(err)) | Err(Err::Failure(err)) => { |
60 | | panic!("Result should not be an error: {:?}.", err); |
61 | | } |
62 | | } |
63 | | } |
64 | | } |