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
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.

use crate::*;

/// Types from which values can be read.
///
/// Values are vectors of bytes, encapsulated in the associated `DBVector` type.
///
/// Method variants here allow for specifying `ReadOptions`, the column family
/// to read from, or to encode the value as a protobuf message.
pub trait Peekable {
    /// The byte-vector type through which the database returns read values.
    type DBVector: DBVector;

    /// Read a value for a key, given a set of options.
    ///
    /// Reads from the default column family.
    ///
    /// Returns `None` if they key does not exist.
    fn get_value_opt(&self, opts: &ReadOptions, key: &[u8]) -> Result<Option<Self::DBVector>>;

    /// Read a value for a key from a given column family, given a set of options.
    ///
    /// Returns `None` if the key does not exist.
    fn get_value_cf_opt(
        &self,
        opts: &ReadOptions,
        cf: &str,
        key: &[u8],
    ) -> Result<Option<Self::DBVector>>;

    /// Read a value for a key.
    ///
    /// Uses the default options and column family.
    ///
    /// Returns `None` if the key does not exist.
    fn get_value(&self, key: &[u8]) -> Result<Option<Self::DBVector>> {
        self.get_value_opt(&ReadOptions::default(), key)
    }

    /// Read a value for a key from a given column family.
    ///
    /// Uses the default options.
    ///
    /// Returns `None` if the key does not exist.
    fn get_value_cf(&self, cf: &str, key: &[u8]) -> Result<Option<Self::DBVector>> {
        self.get_value_cf_opt(&ReadOptions::default(), cf, key)
    }

    /// Read a value and return it as a protobuf message.
    fn get_msg<M: protobuf::Message + Default>(&self, key: &[u8]) -> Result<Option<M>> {
        let value = self.get_value(key)?;
        if value.is_none() {
            return Ok(None);
        }

        let mut m = M::default();
        m.merge_from_bytes(&value.unwrap())?;
        Ok(Some(m))
    }

    /// Read a value and return it as a protobuf message.
    fn get_msg_cf<M: protobuf::Message + Default>(
        &self,
        cf: &str,
        key: &[u8],
    ) -> Result<Option<M>> {
        let value = self.get_value_cf(cf, key)?;
        if value.is_none() {
            return Ok(None);
        }

        let mut m = M::default();
        m.merge_from_bytes(&value.unwrap())?;
        Ok(Some(m))
    }
}