lending_library/
loan.rs

1/* Notice
2loan.rs: lending-library
3
4Copyright 2018 Thomas Bytheway <thomas.bytheway@cl.cam.ac.uk>
5
6This file is part of the lending-library open-source project: github.com/harkonenbade/lending-library;
7Its licensing is governed by the LICENSE file at the root of the project.
8*/
9
10use super::LendingLibrary;
11use std::{
12    fmt::{Debug, Error as FmtError, Formatter},
13    hash::Hash,
14    ops::{Deref, DerefMut},
15    thread,
16};
17
18/// A smart pointer representing the loan of a key/value pair from a `LendingLibrary` instance.
19pub struct Loan<K, V>
20where
21    K: Hash,
22{
23    pub(super) owner: *mut LendingLibrary<K, V>,
24    pub(super) key: u64,
25    pub(super) inner: Option<V>,
26}
27
28impl<K, V> Debug for Loan<K, V>
29where
30    K: Hash,
31    V: Debug,
32{
33    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
34        <V as Debug>::fmt(self, f)
35    }
36}
37
38impl<K, V> PartialEq for Loan<K, V>
39where
40    K: Hash,
41    V: PartialEq,
42{
43    fn eq(&self, other: &Self) -> bool {
44        self.inner == other.inner
45    }
46}
47
48impl<K, V> Drop for Loan<K, V>
49where
50    K: Hash,
51{
52    fn drop(&mut self) {
53        if self.inner.is_some() && !thread::panicking() {
54            unsafe {
55                (*self.owner).checkin(self.key, self.inner.take().unwrap());
56            }
57        }
58    }
59}
60
61impl<K, V> Deref for Loan<K, V>
62where
63    K: Hash,
64{
65    type Target = V;
66
67    fn deref(&self) -> &V {
68        self.inner.as_ref().unwrap()
69    }
70}
71
72impl<K, V> DerefMut for Loan<K, V>
73where
74    K: Hash,
75{
76    fn deref_mut(&mut self) -> &mut V {
77        self.inner.as_mut().unwrap()
78    }
79}