phonenumber/parser/
natural.rs

1// Copyright (C) 2017 1aim GmbH
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::consts;
16use crate::parser::helper::*;
17use nom::error::ErrorKind;
18use nom::IResult;
19
20pub fn phone_number(i: &str) -> IResult<&str, Number<'_>> {
21    let (_, i) = extract(i)?;
22    let extension = consts::EXTN_PATTERN.captures(i);
23
24    if let Some(c) = extension.as_ref() {
25        if c.get(0).is_none() || c.get(2).is_none() {
26            return Err(nom::Err::Failure(nom::error::Error::new(i, ErrorKind::Eof)));
27        }
28    }
29
30    Ok((
31        "",
32        Number {
33            national: extension
34                .as_ref()
35                .map(|c| &i[..c.get(0).unwrap().start()])
36                .unwrap_or(i)
37                .into(),
38
39            extension: extension
40                .as_ref()
41                .map(|c| c.get(2).unwrap().as_str())
42                .map(Into::into),
43
44            ..Default::default()
45        },
46    ))
47}
48
49#[cfg(test)]
50mod test {
51    use crate::parser::helper::*;
52    use crate::parser::natural;
53
54    #[test]
55    fn phone_number() {
56        assert_eq!(
57            natural::phone_number("650 253 0000 extn. 4567").unwrap().1,
58            Number {
59                national: "650 253 0000".into(),
60                extension: Some("4567".into()),
61
62                ..Default::default()
63            }
64        );
65    }
66}