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
193
194
195
196
197
198
199
200
201
202
use std::borrow::Cow;
use std::fmt::{self, Debug};

/// A map used for holding query string paramenters or headers
#[derive(Clone)]
pub struct Map<'a> {
    inner: Vec<(Cow<'a, str>, Cow<'a, str>)>,
}

impl<'a> Map<'a> {
    /// Construct a new empty `Map`
    #[inline]
    pub const fn new() -> Self {
        Self { inner: Vec::new() }
    }

    /// Get the number of elements in this `Map`
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Return `true` if this `Map` is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get the value of an element of this `Map`, or `None` if it doesn't contain `key`
    pub fn get(&self, key: &str) -> Option<&str> {
        match self.inner.binary_search_by(|a| a.0.as_ref().cmp(key)) {
            Ok(i) => self.inner.get(i).map(|kv| kv.1.as_ref()),
            Err(_) => None,
        }
    }

    /// Insert a new element in this `Map`
    ///
    /// Overwrites elements with the same `key`, if present.
    pub fn insert<K, V>(&mut self, key: K, value: V)
    where
        K: Into<Cow<'a, str>>,
        V: Into<Cow<'a, str>>,
    {
        let key = key.into();
        let value = value.into();

        let i = self.inner.binary_search_by(|a| a.0.cmp(&key));
        match i {
            Ok(i) => {
                let old_value = self.inner.get_mut(i).expect("i can't be out of bounds");
                let new_value = Cow::Owned(format!("{}, {}", old_value.1, value));
                *old_value = (key, new_value);
            }
            Err(i) => self.inner.insert(i, (key, value)),
        }
    }

    /// Remove an element from this `Map` and return it
    pub fn remove(&mut self, key: &str) -> Option<(Cow<'a, str>, Cow<'a, str>)> {
        match self.inner.binary_search_by(|a| a.0.as_ref().cmp(key)) {
            Ok(i) => Some(self.inner.remove(i)),
            Err(_) => None,
        }
    }

    /// Return an `Iterator` over this map
    ///
    /// The elements are always sorted in alphabetical order based on the key.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> + Clone {
        self.inner.iter().map(|t| (t.0.as_ref(), t.1.as_ref()))
    }
}

impl<'a> Debug for Map<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}

impl<'a> Default for Map<'a> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn map() {
        let mut map = Map::new();
        {
            assert_eq!(map.len(), 0);
            assert!(map.is_empty());
            assert!(map.get("nothing").is_none());

            let mut iter = map.iter();
            assert!(iter.next().is_none());
        }

        {
            map.insert("content-type", "text/plain");
            assert_eq!(map.len(), 1);
            assert!(!map.is_empty());
            assert!(map.get("nothing").is_none());
            assert_eq!(map.get("content-type"), Some("text/plain"));

            let iter = map.iter();
            iter.eq(vec![("content-type", "text/plain")].into_iter());
        }

        {
            map.insert("cache-control", "public, max-age=86400");
            assert_eq!(map.len(), 2);
            assert!(!map.is_empty());
            assert!(map.get("nothing").is_none());
            assert_eq!(map.get("content-type"), Some("text/plain"));
            assert_eq!(map.get("cache-control"), Some("public, max-age=86400"));

            let iter = map.iter();
            iter.eq(vec![
                ("cache-control", "public, max-age=86400"),
                ("content-type", "text/plain"),
            ]
            .into_iter());
        }

        {
            map.insert("x-amz-storage-class", "standard");
            assert_eq!(map.len(), 3);
            assert!(!map.is_empty());
            assert!(map.get("nothing").is_none());
            assert_eq!(map.get("content-type"), Some("text/plain"));
            assert_eq!(map.get("cache-control"), Some("public, max-age=86400"));
            assert_eq!(map.get("x-amz-storage-class"), Some("standard"));

            let iter = map.iter();
            iter.eq(vec![
                ("cache-control", "public, max-age=86400"),
                ("content-type", "text/plain"),
                ("x-amz-storage-class", "standard"),
            ]
            .into_iter());
        }

        {
            map.remove("content-type");
            assert_eq!(map.len(), 2);
            assert!(!map.is_empty());
            assert!(map.get("nothing").is_none());
            assert_eq!(map.get("cache-control"), Some("public, max-age=86400"));
            assert_eq!(map.get("x-amz-storage-class"), Some("standard"));

            let iter = map.iter();
            iter.eq(vec![
                ("cache-control", "public, max-age=86400"),
                ("x-amz-storage-class", "standard"),
            ]
            .into_iter());
        }

        {
            map.remove("x-amz-look-at-how-many-headers-you-have");
            assert_eq!(map.len(), 2);
            assert!(!map.is_empty());
            assert!(map.get("nothing").is_none());
            assert_eq!(map.get("cache-control"), Some("public, max-age=86400"));
            assert_eq!(map.get("x-amz-storage-class"), Some("standard"));

            let iter = map.iter();
            iter.eq(vec![
                ("cache-control", "public, max-age=86400"),
                ("x-amz-storage-class", "standard"),
            ]
            .into_iter());
        }

        {
            map.insert("cache-control", "immutable");
            assert_eq!(map.len(), 2);
            assert!(!map.is_empty());
            assert!(map.get("nothing").is_none());
            assert_eq!(
                map.get("cache-control"),
                Some("public, max-age=86400, immutable")
            );
            assert_eq!(map.get("x-amz-storage-class"), Some("standard"));

            let iter = map.iter();
            iter.eq(vec![
                ("cache-control", "public, max-age=86400, immutable"),
                ("x-amz-storage-class", "standard"),
            ]
            .into_iter());
        }
    }
}