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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*
 * request.rs
 *
 * wikidot-path - Library to parse Wikidot-like paths.
 * Copyright (c) 2019-2021 Ammon Smith
 *
 * wikidot-normalize is available free of charge under the terms of the MIT
 * License. You are free to redistribute and/or modify it under those
 * terms. It is distributed in the hopes that it will be useful, but
 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
 *
 */

use std::collections::HashMap;

lazy_static! {
    static ref EMPTY_REQUEST: Request<'static> = Request {
        slug: "",
        category: "_default",
        arguments: hashmap! {},
    };
}

/// Represents a request for a page.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde-derive", derive(Serialize))]
pub struct Request<'a> {
    /// The slug, or URL identifier of a page.
    ///
    /// For a page like "SCP-1000" this will be `scp-1000`.
    pub slug: &'a str,

    /// The category that this page appears in.
    pub category: &'a str,

    /// What arguments were passed into the request.
    /// A mapping of key to value.
    pub arguments: HashMap<&'a str, ArgumentValue<'a>>,
}

impl<'a> Request<'a> {
    /// Parses a path to extract the slug, categories, and arguments.
    /// Makes a best-effort match if the path is not in normal form.
    pub fn parse(mut path: &'a str) -> Self {
        if path.starts_with('/') {
            // Remove leading slash
            path = &path[1..];
        }

        // Create part iterator and get slug
        let mut parts = path.split('/');
        let slug = match parts.next() {
            Some(slug) => slug,
            None => {
                // No slug found, return an empty request
                return EMPTY_REQUEST.clone();
            }
        };

        // Get all page categories
        let (slug, category) = match slug.find(':') {
            // We can't use .split_at() because we want to
            // exclude the ':' from appearing in the string.
            Some(idx) => (&slug[idx + 1..], &slug[..idx]),
            None => (slug, "_default"),
        };

        // Parse out Wikidot arguments
        //
        // This algorithm is compatible with the /KEY/true format,
        // but also allowing the more sensible /KEY for options
        // where a 'false' value doesn't make sense, like 'norender' or 'edit'.
        let arguments = {
            let mut arguments = HashMap::new();

            while let Some(key) = parts.next() {
                if key.is_empty() || key == "true" || key == "false" {
                    continue;
                }

                let value = ArgumentValue::from(parts.next());
                arguments.insert(key, value);
            }

            arguments
        };

        Request {
            slug,
            category,
            arguments,
        }
    }
}

/// A type for possible values an argument key could have.
///
/// Those consuming values should attempt to be flexible when
/// accepting values. For instance a truthy key should accept
/// `1`, `true`, and `Null` (as it indicates that they key is
/// present at all) as meaning "true".
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArgumentValue<'a> {
    /// A string argument value.
    String(&'a str),

    /// An integer argument value.
    Integer(i32),

    /// A boolean argument value.
    Boolean(bool),

    /// No value explicitly passed for this argument.
    Null,
}

cfg_if! {
    if #[cfg(feature = "serde-derive")] {
        use serde::{Serialize, Serializer};

        impl<'a> Serialize for ArgumentValue<'a> {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                use self::ArgumentValue::*;

                match self {
                    String(value) => serializer.serialize_str(value),
                    Boolean(value) => serializer.serialize_bool(*value),
                    Integer(value) => serializer.serialize_i32(*value),
                    Null => serializer.serialize_unit(),
                }
            }
        }
    }
}

impl<'a> From<Option<&'a str>> for ArgumentValue<'a> {
    #[inline]
    fn from(value: Option<&'a str>) -> Self {
        match value {
            Some(value) => ArgumentValue::from(value),
            None => ArgumentValue::Null,
        }
    }
}

impl<'a> From<&'a str> for ArgumentValue<'a> {
    fn from(value: &'a str) -> Self {
        match value {
            "" => ArgumentValue::Null,
            "true" => ArgumentValue::Boolean(true),
            "false" => ArgumentValue::Boolean(false),
            _ => match value.parse::<i32>() {
                Ok(int) => ArgumentValue::Integer(int),
                Err(_) => ArgumentValue::String(value),
            },
        }
    }
}

impl From<bool> for ArgumentValue<'_> {
    #[inline]
    fn from(value: bool) -> Self {
        ArgumentValue::Boolean(value)
    }
}

impl From<i32> for ArgumentValue<'_> {
    #[inline]
    fn from(value: i32) -> Self {
        ArgumentValue::Integer(value)
    }
}

impl From<()> for ArgumentValue<'_> {
    #[inline]
    fn from(_: ()) -> Self {
        ArgumentValue::Null
    }
}