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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#![no_std]
extern crate alloc;

mod deref;
mod index;
mod iter;
#[cfg(feature = "serde")]
mod serde;
#[cfg(test)]
mod tests;

use alloc::vec::Vec;
use core::borrow::Borrow;
use core::fmt::{self, Debug, Formatter};
use core::mem;

pub use iter::{Iter, Keys, Values, ValuesMut};

#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VecBTreeMap<K, V> {
    base: Vec<(K, V)>,
}

impl<K, V> VecBTreeMap<K, V> {
    /// Constructs a new, empty `VecBTreeMap<K, V>`.
    ///
    /// The map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
    ///
    /// # Examples
    ///
    /// ```
    /// # #![allow(unused_mut)]
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map: VecBTreeMap<String, f64> = VecBTreeMap::new();
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self { base: Vec::new() }
    }

    /// Constructs a new, empty `VecBTreeMap<K, V>` with at least the specified capacity.
    ///
    /// The map will be able to hold at least `capacity` elements without
    /// reallocating. This method is allowed to allocate for more elements than
    /// `capacity`. If `capacity` is 0, the map will not allocate.
    ///
    /// It is important to note that although the returned map has the
    /// minimum *capacity* specified, the map will have a zero *length*. For
    /// an explanation of the difference between length and capacity, see
    /// *[Capacity and reallocation]*.
    ///
    /// If it is important to know the exact allocated capacity of a `VecBTreeMap<K, V>`,
    /// always use the [`capacity`] method after construction.
    ///
    /// [Capacity and reallocation]: Vec#capacity-and-reallocation
    /// [`capacity`]: Vec::capacity
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::with_capacity(10);
    ///
    /// // The map contains no items, even though it has capacity for more
    /// assert_eq!(map.len(), 0);
    /// assert!(map.capacity() >= 10);
    ///
    /// // These are all done without reallocating...
    /// for i in 0..10 {
    ///     map.insert(i, i);
    /// }
    /// assert_eq!(map.len(), 10);
    /// assert!(map.capacity() >= 10);
    ///
    /// // ...but this may make the map reallocate
    /// map.insert(11, 0);
    /// assert_eq!(map.len(), 11);
    /// assert!(map.capacity() >= 11);
    /// ```
    ///     
    #[inline]
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            base: Vec::with_capacity(capacity),
        }
    }

    /// An iterator yielding all key-value paris from start to end.
    /// The iterator element type is `(&K, &V)`.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::with_capacity(3);
    /// map.insert("a", 1);
    /// map.insert("b", 2);
    /// map.insert("c", 3);
    ///
    /// let mut iter = map.iter();
    ///
    /// for (key, value) in iter {
    ///     println!("{key}: {value}");
    /// }
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<'_, K, V> {
        Iter::new(self.base.iter())
    }

    /// An iterator yielding all keys from start to end.
    /// The iterator element type is `&K`.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::with_capacity(3);
    /// map.insert("a", 1);
    /// map.insert("b", 2);
    /// map.insert("c", 3);
    ///
    ///let mut keys = map.keys();
    ///
    /// assert_eq!(keys.next(), Some(&"a"));
    /// assert_eq!(keys.next(), Some(&"b"));
    /// assert_eq!(keys.next(), Some(&"c"));
    /// assert_eq!(keys.next(), None);
    /// ```
    #[inline]
    pub fn keys(&self) -> Keys<'_, K, V> {
        Keys::new(self.base.iter())
    }

    /// An iterator yielding all values from start to end.
    /// The iterator element type is `&V`.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::with_capacity(3);
    /// map.insert("a", 1);
    /// map.insert("b", 2);
    /// map.insert("c", 3);
    ///
    ///let mut keys = map.values();
    ///
    /// assert_eq!(keys.next(), Some(&1));
    /// assert_eq!(keys.next(), Some(&2));
    /// assert_eq!(keys.next(), Some(&3));
    /// assert_eq!(keys.next(), None);
    /// ```
    #[inline]
    pub fn values(&self) -> Values<'_, K, V> {
        Values::new(self.base.iter())
    }

    /// An iterator yielding all values mutably from start to end.
    /// The iterator element type is `&V`.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::with_capacity(3);
    /// map.insert("a", 1);
    /// map.insert("b", 2);
    /// map.insert("c", 3);
    ///
    /// for val in map.values_mut() {
    ///     *val *= *val;
    /// }
    ///
    ///let mut keys = map.values();
    ///
    /// assert_eq!(keys.next(), Some(&1));
    /// assert_eq!(keys.next(), Some(&4));
    /// assert_eq!(keys.next(), Some(&9));
    /// assert_eq!(keys.next(), None);
    /// ```
    #[inline]
    pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
        ValuesMut::new(self.base.iter_mut())
    }
}

impl<K, V> VecBTreeMap<K, V>
where
    K: Ord,
{
    /// Binary searches this map for a given key.
    ///
    /// If the key is found then [`Result::Ok`] is returned, containing the
    /// index of the matching key.
    /// If the key is not found then [`Result::Err`] is returned, containing
    /// the index where a matching key-value pair could be inserted while maintaining
    /// sorted order.
    ///
    /// # Examples
    ///
    /// Looks up a series of four elements.
    /// The first is found, the second and third are not.
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::with_capacity(3);
    /// map.insert("a", 1);
    /// map.insert("c", 2);
    /// map.insert("d", 3);
    ///
    /// assert_eq!(map.binary_search("a"), Ok(0));
    /// assert_eq!(map.binary_search("b"), Err(1));
    /// assert_eq!(map.binary_search("e"), Err(3));
    /// ```
    #[inline]
    pub fn binary_search<Q: ?Sized>(&self, k: &Q) -> Result<usize, usize>
    where
        K: Borrow<Q>,
        Q: Ord,
    {
        self.base.binary_search_by(|e| e.0.borrow().cmp(k))
    }

    /// Appends a key-value pair to the back of the map.
    ///
    /// If the map woudn't be sorted anymore by appending
    /// the key-value pair to the back of the map, [`Some`]`(K, V)` is returned.
    /// Otherwise [`None`] is returned.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    #[inline]
    pub fn push(&mut self, k: K, v: V) -> Option<(K, V)> {
        let last = self.len().saturating_sub(1);
        if let Some((key, _)) = self.get(last) {
            if key >= &k {
                return Some((k, v));
            }
        }
        self.base.push((k, v));
        None
    }

    /// Inserts a key-value pair into the map.
    ///
    /// If the map did not have this key present, [`None`] is returned.
    ///
    /// If the map did have this key present, the value is updated, and the old
    /// value is returned. The key is not updated.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity exceeds `isize::MAX` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::new();
    ///
    /// assert_eq!(map.is_empty(), true);
    /// assert_eq!(map.insert("a", 1), None);
    /// assert_eq!(map.is_empty(), false);
    ///
    /// map.insert("a", 2);
    /// assert_eq!(map.insert("a", 3), Some(2));
    /// assert_eq!(map[0], 3);
    /// ```
    #[inline]
    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
        match self.binary_search(&k) {
            Ok(i) => Some(mem::replace(&mut self.base[i].1, v)),
            Err(i) => {
                self.base.insert(i, (k, v));
                None
            }
        }
    }

    /// Removes a key from the map, returning the value at the key if the key
    /// was previously in the map.
    ///
    /// The key may be any borrowed form of the map's key type, but
    /// [`Ord`] on the borrowed form *must* match those for
    /// the key type.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::new();
    /// map.insert("a", 1);
    /// assert_eq!(map.remove("a"), Some(1));
    /// assert_eq!(map.remove("a"), None);
    /// ```
    #[inline]
    pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Ord,
    {
        self.binary_search(k).map(|i| self.base.remove(i).1).ok()
    }

    /// Removes the last key-value pair from the map and returns it, or [`None`] if it
    /// is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut map = VecBTreeMap::new();
    /// map.insert("a", 1);
    /// assert_eq!(map.pop(), Some(("a", 1)));
    /// assert_eq!(map.pop(), None);
    /// ```
    #[inline]
    pub fn pop(&mut self) -> Option<(K, V)> {
        self.base.pop()
    }

    /// Clears the map, removing all key-value pairs. Keeps the allocated memory
    /// for reuse.
    ///
    /// # Examples
    ///
    /// ```
    /// use vec_btree_map::VecBTreeMap;
    ///
    /// let mut a = VecBTreeMap::new();
    /// a.insert(1, "a");
    /// a.clear();
    /// assert!(a.is_empty());
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.base.clear()
    }
}

impl<K: Clone, V: Clone> Clone for VecBTreeMap<K, V> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            base: self.base.clone(),
        }
    }
}

impl<K: Debug, V: Debug> Debug for VecBTreeMap<K, V> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self.iter()).finish()
    }
}