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
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Boolean Humanization
//!
//! ## Parsing
//!
//! For all languages, we support parsing `"1"` and `"0"` as `true`
//! and `false` respectively.
//!
//! In English, these lexical values map to `true`:
//!
//! * `"ok"`
//! * `"okay"`
//! * `"on"`
//! * `"true"`
//! * `"yep"`
//! * `"yes"`
//!
//! and these to `false`:
//!
//! * `"false"`
//! * `"no"`
//! * `"nope"`
//! * `"off"`

use language_tags::LanguageTag;
use super::parser::Parse;

impl Parse for bool {
    fn parse(text: &str, language: &LanguageTag) -> Option<bool> {
        let en = langtag!(en);
        match &*text.to_lowercase() {
            "1" => Some(true),
            "0" => Some(false),
            "ok" | "okay" | "on" | "true" | "yep" | "yes" if language.matches(&en) => Some(true),
            "false" | "no" | "nope" | "off" if language.matches(&en) => Some(false),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use {parse, parse_with_language};

    #[test]
    fn basic() {
        assert_eq!(Some(true), parse::<bool>("1"));
        assert_eq!(Some(true), parse::<bool>("ok"));
        assert_eq!(Some(true), parse::<bool>("okay"));
        assert_eq!(Some(true), parse::<bool>("on"));
        assert_eq!(Some(true), parse::<bool>("true"));
        assert_eq!(Some(true), parse::<bool>("yep"));
        assert_eq!(Some(true), parse::<bool>("yes"));

        assert_eq!(Some(false), parse::<bool>("0"));
        assert_eq!(Some(false), parse::<bool>("false"));
        assert_eq!(Some(false), parse::<bool>("no"));
        assert_eq!(Some(false), parse::<bool>("nope"));
        assert_eq!(Some(false), parse::<bool>("off"));

        let badlang = langtag!("no");
        assert_eq!(Some(true), parse_with_language::<bool>("1", &badlang));
        assert_eq!(Some(false), parse_with_language::<bool>("0", &badlang));
        assert_eq!(None, parse_with_language::<bool>("okay", &badlang));
        assert_eq!(None, parse_with_language::<bool>("nope", &badlang));
    }
}