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
use std::borrow::{Borrow, BorrowMut};
use std::io;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

use bytehash::ByteHash;
use owning_ref::{OwningRef, OwningRefMut, StableAddress};

use crate::branch::{Branch, BranchMut};
use crate::compound::Compound;
use crate::content::Content;
use crate::iter::{LeafIter, LeafIterMut};
use crate::search::{First, Method};
use crate::sink::Sink;
use crate::source::Source;

/// A Key-value pair type
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct KV<K, V> {
    /// the key of the pair
    pub key: K,
    /// the value of the pair
    pub val: V,
}

impl<K, V> KV<K, V> {
    /// Create a new key-value pair
    pub fn new(key: K, val: V) -> Self {
        KV { key, val }
    }
}

impl<K, V> Into<(K, V)> for KV<K, V> {
    fn into(self) -> (K, V) {
        (self.key, self.val)
    }
}

impl<K, V, H> Content<H> for KV<K, V>
where
    K: Content<H>,
    V: Content<H>,
    H: ByteHash,
{
    fn persist(&mut self, sink: &mut Sink<H>) -> io::Result<()> {
        self.key.persist(sink)?;
        self.val.persist(sink)
    }
    /// Restore the type from a `Source`
    fn restore(source: &mut Source<H>) -> io::Result<Self> {
        Ok(KV {
            key: K::restore(source)?,
            val: V::restore(source)?,
        })
    }
}

impl<K, V> Borrow<V> for KV<K, V> {
    fn borrow(&self) -> &V {
        &self.val
    }
}

impl<K, V> AsRef<K> for KV<K, V> {
    fn as_ref(&self) -> &K {
        &self.key
    }
}

impl<K, V> BorrowMut<V> for KV<K, V> {
    fn borrow_mut(&mut self) -> &mut V {
        &mut self.val
    }
}

/// A path to a leaf in a map Compound
pub struct ValPath<'a, K, V, C, H>
where
    C: Compound<H>,
    H: ByteHash,
{
    branch: Branch<'a, C, H>,
    _marker: PhantomData<(K, V)>,
}

/// A path to a mutable leaf in a map Compound
pub struct ValPathMut<'a, K, V, C, H>
where
    C: Compound<H>,
    H: ByteHash,
{
    branch: BranchMut<'a, C, H>,
    _marker: PhantomData<(K, V)>,
}

// The following
unsafe impl<'a, K, V, C, H> StableAddress for ValPath<'a, K, V, C, H>
where
    C: Compound<H>,
    C::Leaf: Borrow<V>,
    H: ByteHash,
{
}
unsafe impl<'a, K, V, C, H> StableAddress for ValPathMut<'a, K, V, C, H>
where
    C: Compound<H>,
    C::Leaf: Borrow<V>,
    H: ByteHash,
{
}

impl<'a, K, V, C, H> ValPath<'a, K, V, C, H>
where
    C: Compound<H>,
    H: ByteHash,
{
    /// Creates a new `ValPath`, when leaf is found and key matches
    pub fn new<M>(node: &'a C, method: &mut M) -> io::Result<Option<Self>>
    where
        M: Method<C, H>,
    {
        Ok(Branch::new(node, method)?
            .filter(|branch| branch.exact())
            .map(|branch| ValPath {
                branch,
                _marker: PhantomData,
            }))
    }
}

impl<'a, K, V, C, H> ValPathMut<'a, K, V, C, H>
where
    C: Compound<H>,
    H: ByteHash,
{
    /// Creates a new `ValPathMut`
    pub fn new<M>(node: &'a mut C, method: &mut M) -> io::Result<Option<Self>>
    where
        M: Method<C, H>,
    {
        Ok(BranchMut::new(node, method)?
            .filter(|branch| branch.exact())
            .map(|branch| ValPathMut {
                branch,
                _marker: PhantomData,
            }))
    }
}

impl<'a, K, V, C, H> Deref for ValPath<'a, K, V, C, H>
where
    C: Compound<H>,
    C::Leaf: Borrow<V>,
    H: ByteHash,
{
    type Target = V;

    fn deref(&self) -> &Self::Target {
        (*self.branch).borrow()
    }
}

impl<'a, K, V, C, H> Deref for ValPathMut<'a, K, V, C, H>
where
    C: Compound<H>,
    C::Leaf: Borrow<V>,
    H: ByteHash,
{
    type Target = V;

    fn deref(&self) -> &Self::Target {
        (*self.branch).borrow()
    }
}

impl<'a, K, V, C, H> DerefMut for ValPathMut<'a, K, V, C, H>
where
    C: Compound<H>,
    C::Leaf: BorrowMut<V>,
    H: ByteHash,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        (*self.branch).borrow_mut()
    }
}

pub struct ValIter<'a, C, V, M, H>(LeafIter<'a, C, M, H>, PhantomData<V>)
where
    C: Compound<H>,
    H: ByteHash;

pub struct ValIterMut<'a, C, V, M, H>(LeafIterMut<'a, C, M, H>, PhantomData<V>)
where
    C: Compound<H>,
    H: ByteHash;

pub struct KeyIter<'a, C, K, V, M, H>(
    LeafIter<'a, C, M, H>,
    PhantomData<(K, V)>,
)
where
    C: Compound<H>,
    H: ByteHash;

/// Compound can be iterated over like a map
pub trait ValIterable<V, H>
where
    Self: Compound<H>,
    H: ByteHash,
{
    /// Iterator over the values of the map
    fn values(&self) -> ValIter<Self, V, First, H>;

    /// Iterator over the mutable values of the map
    fn values_mut(&mut self) -> ValIterMut<Self, V, First, H>;
}

/// Compound can have its values iterated over
impl<C, V, H> ValIterable<V, H> for C
where
    C: Compound<H>,
    H: ByteHash,
{
    fn values(&self) -> ValIter<Self, V, First, H> {
        ValIter(LeafIter::Initial(self, First), PhantomData)
    }

    fn values_mut(&mut self) -> ValIterMut<Self, V, First, H> {
        ValIterMut(LeafIterMut::Initial(self, First), PhantomData)
    }
}

impl<'a, C, V, M, H> Iterator for ValIter<'a, C, V, M, H>
where
    C: Compound<H>,
    C::Leaf: Borrow<V>,
    M: 'a + Method<C, H>,
    V: 'a,
    H: ByteHash,
{
    type Item = io::Result<&'a V>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0.next() {
            Some(Ok(leaf)) => Some(Ok(leaf.borrow())),
            Some(Err(e)) => Some(Err(e)),
            None => None,
        }
    }
}

impl<'a, C, V, M, H> Iterator for ValIterMut<'a, C, V, M, H>
where
    C: Compound<H>,
    C::Leaf: BorrowMut<V>,
    M: 'a + Method<C, H>,
    V: 'a,
    H: ByteHash,
{
    type Item = io::Result<&'a mut V>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0.next() {
            Some(Ok(leaf)) => Some(Ok(leaf.borrow_mut())),
            Some(Err(e)) => Some(Err(e)),
            None => None,
        }
    }
}

impl<'a, C, K, V, M, H> Iterator for KeyIter<'a, C, K, V, M, H>
where
    C: Compound<H>,
    C::Leaf: Borrow<K>,
    M: 'a + Method<C, H>,
    K: 'a,
    V: 'a,
    H: ByteHash,
{
    type Item = io::Result<&'a K>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0.next() {
            Some(Ok(leaf)) => Some(Ok(leaf.borrow())),
            Some(Err(e)) => Some(Err(e)),
            None => None,
        }
    }
}

/// Value reference trait to hide generic arguments to users of the library
pub trait ValRef<'a, V: 'a>: Deref<Target = V> + 'a
where
    Self: Sized + StableAddress,
{
    /// Wrap the ValPath in an OwningRef
    fn wrap<V2, F>(self, f: F) -> OwningRef<Self, V2>
    where
        V2: 'a,
        F: for<'r> FnOnce(&'r V) -> &'r V2,
    {
        OwningRef::new(self).map(f)
    }
}
impl<'a, T, V: 'a> ValRef<'a, V> for T where
    T: StableAddress + Deref<Target = V> + 'a
{
}

/// Mutable value reference trait to hide generic arguments to users of the library
pub trait ValRefMut<'a, V>: DerefMut<Target = V> + 'a
where
    Self: Sized + StableAddress,
{
    /// Wrap the ValPathMut in an OwningRef
    fn wrap_mut<V2, F>(self, f: F) -> OwningRefMut<Self, V2>
    where
        V2: 'a,
        F: for<'r> FnOnce(&'r mut V) -> &'r mut V2,
    {
        OwningRefMut::new(self).map_mut(f)
    }
}

impl<'a, T, V> ValRefMut<'a, V> for T where
    T: StableAddress + Deref<Target = V> + 'a + DerefMut + 'a
{
}

/// Collection can be read as a map
pub trait Map<'a, K, O, V, H>
where
    Self: Compound<H>,
    Self::Leaf: Borrow<V>,
    K: Borrow<O> + 'a,
    O: ?Sized + 'a,
    H: ByteHash,
{
    /// The method used to search for keys in the structure
    type KeySearch: Method<Self, H> + From<&'a O>;

    /// Returns a reference to a value in the map, if any
    fn get(&self, k: &'a O) -> io::Result<Option<ValPath<K, V, Self, H>>> {
        ValPath::new(self, &mut Self::KeySearch::from(k.borrow()))
    }

    /// Returns a reference to a mutable value in the map, if any
    fn get_mut(
        &mut self,
        k: &'a O,
    ) -> io::Result<Option<ValPathMut<K, V, Self, H>>> {
        ValPathMut::new(self, &mut Self::KeySearch::from(k.borrow()))
    }
}