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
180
181
182
183
184
185
186
187
188
189
190
191
192
use crate::Status;
use http::StatusCode;
use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Display;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;

pub trait Value: Any + Send + Sync {}

impl<V> Value for V where V: Any + Send + Sync {}

/// A context scoped storage.
#[derive(Clone)]
pub struct Storage(
    HashMap<TypeId, HashMap<Cow<'static, str>, Arc<dyn Any + Send + Sync>>>,
);

/// A wrapper of Arc.
///
/// ### Deref
///
/// ```rust
/// use roa_core::Variable;
///
/// fn consume<V>(var: Variable<V>) {
///     let value: &V = &var;
/// }
/// ```
///
/// ### Parse
///
/// ```rust
/// use roa_core::{Variable, Result};
///
/// fn consume<V: AsRef<str>>(var: Variable<V>) -> Result {
///     let value: i32 = var.parse()?;
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Variable<'a, V> {
    key: &'a str,
    value: Arc<V>,
}

impl<V> Deref for Variable<'_, V> {
    type Target = V;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<'a, V> Variable<'a, V> {
    /// Construct a variable from name and value.
    #[inline]
    fn new(key: &'a str, value: Arc<V>) -> Self {
        Self { key, value }
    }

    /// Consume self and get inner Arc<T>.
    #[inline]
    pub fn value(self) -> Arc<V> {
        self.value
    }
}

impl<V> Variable<'_, V>
where
    V: AsRef<str>,
{
    /// A wrapper of `str::parse`. Converts `T::FromStr::Err` to `roa_core::Error` automatically.
    #[inline]
    pub fn parse<T>(&self) -> Result<T, Status>
    where
        T: FromStr,
        T::Err: Display,
    {
        self.as_ref().parse().map_err(|err| {
            Status::new(
                StatusCode::BAD_REQUEST,
                format!(
                    "{}\ntype of variable `{}` should be {}",
                    err,
                    self.key,
                    std::any::type_name::<T>()
                ),
                true,
            )
        })
    }
}

impl Storage {
    /// Construct an empty Bucket.
    #[inline]
    pub fn new() -> Self {
        Self(HashMap::new())
    }

    /// Inserts a key-value pair into the storage.
    ///
    /// If the storage did not have this key present, [`None`] is returned.
    ///
    /// If the storage did have this key present, the value is updated, and the old
    /// value is returned.
    pub fn insert<S, K, V>(&mut self, scope: S, key: K, value: V) -> Option<Arc<V>>
    where
        S: Any,
        K: Into<Cow<'static, str>>,
        V: Value,
    {
        let id = TypeId::of::<S>();
        match self.0.get_mut(&id) {
            Some(bucket) => bucket
                .insert(key.into(), Arc::new(value))
                .and_then(|value| Some(value.downcast().ok()?)),
            None => {
                self.0.insert(id, HashMap::new());
                self.insert(scope, key, value)
            }
        }
    }

    /// If the storage did not have this key present, [`None`] is returned.
    ///
    /// If the storage did have this key present, the key-value pair will be returned as a `Variable`
    #[inline]
    pub fn get<'a, S, V>(&self, key: &'a str) -> Option<Variable<'a, V>>
    where
        S: Any,
        V: Value,
    {
        let value = self.0.get(&TypeId::of::<S>())?.get(key)?.clone();
        Some(Variable::new(key, value.clone().downcast().ok()?))
    }
}

impl Default for Storage {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::{Storage, Variable};
    use http::StatusCode;
    use std::sync::Arc;

    #[test]
    fn storage() {
        struct Scope;

        let mut storage = Storage::default();
        assert!(storage.get::<Scope, &'static str>("id").is_none());
        assert!(storage.insert(Scope, "id", "1").is_none());
        let id: i32 = storage
            .get::<Scope, &'static str>("id")
            .unwrap()
            .parse()
            .unwrap();
        assert_eq!(1, id);
        assert_eq!(
            1,
            storage
                .insert(Scope, "id", "2")
                .unwrap()
                .parse::<i32>()
                .unwrap()
        );
    }

    #[test]
    fn variable() {
        assert_eq!(
            1,
            Variable::new("id", Arc::new("1")).parse::<i32>().unwrap()
        );
        let result = Variable::new("id", Arc::new("x")).parse::<usize>();
        assert!(result.is_err());
        let status = result.unwrap_err();
        assert_eq!(StatusCode::BAD_REQUEST, status.status_code);
        assert!(status
            .message
            .ends_with("type of variable `id` should be usize"));
    }
}