ip_combinator/lib.rs
1/**
2 * The MIT License (MIT)
3 * Copyright (c) 2016 Jean Pierre Dudey
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 */
23
24#[macro_use]
25extern crate nom;
26
27use nom::is_digit;
28use std::str::FromStr;
29use std::net::Ipv4Addr;
30
31named!(dot, tag!("."));
32
33named!(d8<u8>, map!(take_while!(is_digit), |digits: &[u8]| -> u8 {
34 if digits.len() > 3 {
35 return 0;
36 }
37
38 let u8_str = match std::str::from_utf8(digits) {
39 Ok(s) => s,
40 Err(_) => return 0,
41 };
42
43 match u8::from_str(u8_str) {
44 Ok(val) => return val,
45 Err(_) => return 0,
46 }
47}));
48
49named!(pub ipv4_address<&[u8], Ipv4Addr>, chain!(a: d8 ~
50 dot ~
51 b: d8 ~
52 dot ~
53 c: d8 ~
54 dot ~
55 d: d8,
56 || { Ipv4Addr::new(a, b, c, d) }));
57
58#[cfg(test)]
59mod test {
60 #[test]
61 fn check_ipv4_address() {
62 use super::ipv4_address;
63 use super::nom::IResult;
64 use std::net::Ipv4Addr;
65
66 let to_parse = b"192.168.1.1";
67 let exp_out = Ipv4Addr::new(192, 168, 1, 1);
68 let exp_in = b"";
69
70 match ipv4_address(to_parse) {
71 IResult::Done(in_, out) => {
72 assert_eq!(out, exp_out);
73 assert_eq!(in_, exp_in);
74 },
75 IResult::Incomplete(x) => panic!("incomplete: {:?}", x),
76 IResult::Error(e) => panic!("error: {:?}", e),
77 }
78 }
79}