wikidot_path/
value.rs

1/*
2 * value.rs
3 *
4 * wikidot-path - Library to parse Wikidot-like paths.
5 * Copyright (c) 2019-2023 Emmie Maeda
6 *
7 * wikidot-normalize is available free of charge under the terms of the MIT
8 * License. You are free to redistribute and/or modify it under those
9 * terms. It is distributed in the hopes that it will be useful, but
10 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
11 *
12 */
13
14/// A type for possible values an argument key could have.
15///
16/// Those consuming values should attempt to be flexible when
17/// accepting values. For instance a truthy key should accept
18/// `1`, `true`, and `Null` (as it indicates that they key is
19/// present at all) as meaning "true".
20#[derive(Debug, Copy, Clone, PartialEq, Eq)]
21pub enum ArgumentValue<'a> {
22    /// A string argument value.
23    String(&'a str),
24
25    /// An integer argument value.
26    Integer(i32),
27
28    /// A boolean argument value.
29    Boolean(bool),
30
31    /// No value explicitly passed for this argument.
32    /// It notes that the key was included in the mapping.
33    Null,
34}
35
36impl<'a> From<Option<&'a str>> for ArgumentValue<'a> {
37    #[inline]
38    fn from(value: Option<&'a str>) -> Self {
39        match value {
40            Some(value) => ArgumentValue::from(value),
41            None => ArgumentValue::Null,
42        }
43    }
44}
45
46impl<'a> From<&'a str> for ArgumentValue<'a> {
47    fn from(value: &'a str) -> Self {
48        const SPECIAL_VALUES: [(&str, ArgumentValue); 5] = [
49            ("", ArgumentValue::Null),
50            ("t", ArgumentValue::Boolean(true)),
51            ("f", ArgumentValue::Boolean(false)),
52            ("true", ArgumentValue::Boolean(true)),
53            ("false", ArgumentValue::Boolean(false)),
54        ];
55
56        for (name, result) in &SPECIAL_VALUES {
57            if name.eq_ignore_ascii_case(value) {
58                return *result;
59            }
60        }
61
62        match value.parse::<i32>() {
63            Ok(int) => ArgumentValue::Integer(int),
64            Err(_) => ArgumentValue::String(value),
65        }
66    }
67}
68
69impl From<bool> for ArgumentValue<'_> {
70    #[inline]
71    fn from(value: bool) -> Self {
72        ArgumentValue::Boolean(value)
73    }
74}
75
76impl From<i32> for ArgumentValue<'_> {
77    #[inline]
78    fn from(value: i32) -> Self {
79        ArgumentValue::Integer(value)
80    }
81}
82
83impl From<()> for ArgumentValue<'_> {
84    #[inline]
85    fn from(_: ()) -> Self {
86        ArgumentValue::Null
87    }
88}