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
use crate::engine::scrypto_env::ScryptoVmV1Api;
use radix_engine_interface::api::key_value_entry_api::KeyValueEntryHandle;
use radix_engine_interface::data::scrypto::*;
use radix_engine_interface::types::SubstateHandle;
use sbor::rust::fmt;
use sbor::rust::marker::PhantomData;
use sbor::rust::ops::{Deref, DerefMut};

pub struct KeyValueEntryRef<'a, V: ScryptoEncode> {
    lock_handle: KeyValueEntryHandle,
    value: V,
    phantom: PhantomData<&'a ()>,
}

impl<'a, V: fmt::Display + ScryptoEncode> fmt::Display for KeyValueEntryRef<'a, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(f)
    }
}

impl<'a, V: ScryptoEncode> KeyValueEntryRef<'a, V> {
    pub fn new(lock_handle: KeyValueEntryHandle, value: V) -> KeyValueEntryRef<'a, V> {
        KeyValueEntryRef {
            lock_handle,
            value,
            phantom: PhantomData::default(),
        }
    }
}

impl<'a, V: ScryptoEncode> Deref for KeyValueEntryRef<'a, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<'a, V: ScryptoEncode> Drop for KeyValueEntryRef<'a, V> {
    fn drop(&mut self) {
        ScryptoVmV1Api::kv_entry_close(self.lock_handle);
    }
}

pub struct KeyValueEntryRefMut<'a, V: ScryptoEncode> {
    handle: KeyValueEntryHandle,
    value: V,
    phantom: PhantomData<&'a ()>,
}

impl<V: fmt::Display + ScryptoEncode> fmt::Display for KeyValueEntryRefMut<'_, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(f)
    }
}

impl<'a, V: ScryptoEncode> KeyValueEntryRefMut<'a, V> {
    pub fn new(lock_handle: SubstateHandle, value: V) -> KeyValueEntryRefMut<'a, V> {
        KeyValueEntryRefMut {
            handle: lock_handle,
            value,
            phantom: PhantomData::default(),
        }
    }
}

impl<'a, V: ScryptoEncode> Drop for KeyValueEntryRefMut<'a, V> {
    fn drop(&mut self) {
        let value = scrypto_encode(&self.value).unwrap();
        ScryptoVmV1Api::kv_entry_write(self.handle, value);
        ScryptoVmV1Api::kv_entry_close(self.handle);
    }
}

impl<'a, V: ScryptoEncode> Deref for KeyValueEntryRefMut<'a, V> {
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<'a, V: ScryptoEncode> DerefMut for KeyValueEntryRefMut<'a, V> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}