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
#![feature(generic_associated_types, associated_type_defaults)]

use std::borrow::Borrow;
use std::ops::Deref;

pub trait MapGuard<'a, T>: Deref + std::marker::Sized {}


impl<'a, T> MapGuard<'a, T> for &'a T where T: 'a {}

// pub struct RefGuard<'a, T>(&'a T);
// impl<'a, T> Deref for RefGuard<'a, T> {
//     type Target = T;

//     fn deref(&self) -> &Self::Target {
//         self.0
//     }
// }
// impl<'a, T> MapGuard<'a, T> for RefGuard<'a, T> where T: 'a {}


pub trait Map<K, V> {
    type GetGuard<'a>: MapGuard<'a, V>;

    fn get<'a, Q: ?Sized>(&'a self, k: &Q) -> Option<Self::GetGuard<'a>> where K: Borrow<Q>;
    fn insert(&mut self, k: K, v: V) -> Option<V>;
}


#[cfg(test)]
mod tests {
    use super::*;

    fn assert_map_get<K, V>(map: impl Map<K, V>, k: K, v: V) {
        assert_eq!(map.get(&k), Some(v));
    }
    fn assert_map_insert<K, V>(map: impl Map<K, V>, k: K, v: V, o: Option<V>) {
        assert_eq!(map.insert(k, v), o);
    }
}