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
use crate::{IndexTreeMap, Key, Value};

impl<K: Key, V: Value> IndexTreeMap<K, V> {
    /// Replaces an item from the map from it's corresponding key, returning the key-value pair was previously in the map.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```rust
    /// use indextreemap::IndexTreeMap;
    ///
    /// let mut tree = IndexTreeMap::new();
    /// tree.insert(1, "a".to_string());
    /// tree.replace(1, "b".to_string());
    /// assert_eq!(tree.get(&1), Some(&"b".to_string()));
    /// ```
    pub fn replace(&mut self, key: K, value: V) {
        if self.contains_key(&key) {
            self.root.insert(key, Some(value));
        }
    }

    /// Replaces an item from the map from it's corresponding index, returning the key-value pair was previously in the map.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```rust
    /// use indextreemap::IndexTreeMap;
    ///
    /// let mut tree = IndexTreeMap::new();
    /// tree.insert(1, "a".to_string());
    /// tree.replace_index(0, "b".to_string());
    /// assert_eq!(tree.get(&1), Some(&"b".to_string()));
    /// ```
    pub fn replace_index(&mut self, index: usize, value: V) {
        if self.contains_index(index) {
            let key = self.get_key_from_index(index).unwrap();
            self.root.insert(key.to_owned(), Some(value));
        }
    }
}