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
//! An ORM wrapper for Rust [`leveldb`] [`leveldb::database::kv::KV`] APIs. Use [`bincode`] to encoder / decoder key and object. 
//!
//! [`leveldb::database::kv::KV`]: http://skade.github.io/leveldb/leveldb/database/kv/trait.KV.html
//! [`leveldb`]: https://crates.io/crates/leveldb
//! 
//! #### Example
//! This example shows the quickest way to get started with feature `macros`
//! 
//! ```toml
//! [dependencies]
//! leveldb = "0.8"
//! leveldb-orm = { version = "0.1", features = ["macros"]}
//! serde = { version = "1.0", features = ["derive"] }
//! ```
//!
//! ```rust
//! use leveldb::database::Database;
//! use leveldb::options::Options;
//! use leveldb_orm::{KVOrm, KeyOrm, LevelDBOrm};
//! use serde::{Deserialize, Serialize};
//! 
//! #[derive(LevelDBOrm, Serialize, Deserialize)]
//! #[level_db_key(executable, args)]
//! pub struct Command {
//!     pub executable: u8,
//!     pub args: Vec<String>,
//!     pub current_dir: Option<String>,
//! }
//! 
//! let cmd = Command {
//!     executable: 1,
//!     args: vec!["arg1".into(), "arg2".into(), "arg3".into()],
//!     current_dir: Some("\\dir".into()),
//! };
//! 
//! let mut options = Options::new();
//! options.create_if_missing = true;
//! let database = Database::open(std::path::Path::new("./mypath"), options).unwrap();
//! 
//! cmd.put(&database).unwrap();
//! 
//! let key = Command::encode_key((&cmd.executable, &cmd.args)).unwrap();
//! // or `let key = cmd.key().unwrap();`
//! Command::get(&database, &key).unwrap();
//! 
//! Command::delete(&database, false, &key).unwrap();
//! ```

#[cfg(feature = "macros")]
pub use ::leveldb_orm_derive::LevelDBOrm;

use leveldb::database::Database;
use leveldb::kv::KV;
use leveldb::options::ReadOptions;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::marker::PhantomData;

/// The key for leveldb, which impled [`db_key::Key`]. (db-key 0.0.5 only impl it for i32)
/// You can serialize you key to Vec<u8> / &\[u8\] and into EncodedKey.
///
/// [`db_key::Key`]: https://crates.io/crates/db-key/0.0.5
#[derive(Debug, PartialEq)]
pub struct EncodedKey<T: 'static> {
    pub inner: Vec<u8>,
    phantom: PhantomData<T>,
}

impl<T> db_key::Key for EncodedKey<T> {
    #[inline]
    fn from_u8(key: &[u8]) -> Self {
        EncodedKey {
            inner: key.into(),
            phantom: PhantomData,
        }
    }
    #[inline]
    fn as_slice<S, F: Fn(&[u8]) -> S>(&self, f: F) -> S {
        f(&self.inner)
    }
}

impl<T> From<Vec<u8>> for EncodedKey<T> {
    #[inline]
    fn from(inner: Vec<u8>) -> Self {
        EncodedKey {
            inner,
            phantom: PhantomData,
        }
    }
}

impl<'a, T> From<&[u8]> for EncodedKey<T> {
    #[inline]
    fn from(v: &[u8]) -> Self {
        EncodedKey {
            inner: v.into(),
            phantom: PhantomData,
        }
    }
}

/// Interface of key encode / decode
pub trait KeyOrm<'a>: Sized {
    type KeyType: DeserializeOwned;
    type KeyTypeRef: Serialize + 'a;

    /// Without `macros` feature, you can impl `encode_key` by yourself
    #[cfg(not(feature = "macros"))]
    fn encode_key(
        key: Self::KeyTypeRef,
    ) -> std::result::Result<EncodedKey<Self>, Box<dyn std::error::Error>>;

    /// With `macros` feature, the key encodes by [`bincode`]
    #[cfg(feature = "macros")]
    #[inline]
    fn encode_key(
        key: Self::KeyTypeRef,
    ) -> std::result::Result<EncodedKey<Self>, Box<dyn std::error::Error>> {
        bincode::serialize(&key)
            .map(EncodedKey::from)
            .map_err(|e| e.into())
    }

    /// Without `macros` feature, you can impl `decode_key` by yourself
    #[cfg(not(feature = "macros"))]
    fn decode_key(
        data: &EncodedKey<Self>,
    ) -> std::result::Result<Self::KeyType, Box<dyn std::error::Error>>;

    /// With `macros` feature, the key decodes by [`bincode`]
    #[cfg(feature = "macros")]
    #[inline]
    fn decode_key(
        data: &EncodedKey<Self>,
    ) -> std::result::Result<Self::KeyType, Box<dyn std::error::Error>> {
        bincode::deserialize(&data.inner).map_err(|e| e.into())
    }

    /// `#[derive(LevelDBOrm)]` + `#[level_db_key(...)]` could auto impl this function, without derive macro you can impl it manully
    fn key(&self) -> std::result::Result<EncodedKey<Self>, Box<dyn std::error::Error>>;
}

/// An orm version of [`leveldb::database::kv::KV`](http://skade.github.io/leveldb/leveldb/database/kv/trait.KV.html)
pub trait KVOrm<'a>: KeyOrm<'a> + Serialize + DeserializeOwned {
    /// Encode `Self` by [`bincode`]
    #[inline]
    fn encode(&self) -> std::result::Result<Vec<u8>, Box<dyn std::error::Error>> {
        bincode::serialize(self).map_err(|e| e.into())
    }

    /// Decode to `Self` by [`bincode`]
    #[inline]
    fn decode(data: &[u8]) -> std::result::Result<Self, Box<dyn std::error::Error>> {
        bincode::deserialize(data).map_err(|e| e.into())
    }

    /// Refer to [leveldb::database::kv::KV::put](http://skade.github.io/leveldb/leveldb/database/kv/trait.KV.html#tymethod.put)
    fn put_sync(
        &self,
        db: &Database<EncodedKey<Self>>,
        sync: bool,
    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let key = self.key()?;
        let value = self.encode()?;
        db.put(leveldb::options::WriteOptions { sync }, key, &value)
            .map_err(|e| e.into())
    }

    /// With default sync = false
    fn put(
        &self,
        db: &Database<EncodedKey<Self>>,
    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
        self.put_sync(db, false)
    }

    /// Refer to [leveldb::database::kv::KV::get](http://skade.github.io/leveldb/leveldb/database/kv/trait.KV.html#tymethod.get)
    fn get_with_option(
        db: &Database<EncodedKey<Self>>,
        options: ReadOptions<'a, EncodedKey<Self>>,
        key: &EncodedKey<Self>,
    ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
        if let Some(data) = db.get(options, key)? {
            Ok(Some(bincode::deserialize(&data)?))
        } else {
            Ok(None)
        }
    }

    /// With default `ReadOptions`
    fn get(
        db: &Database<EncodedKey<Self>>,
        key: &EncodedKey<Self>,
    ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
        Self::get_with_option(db, ReadOptions::new(), key)
    }

    /// Refer to [leveldb::database::kv::KV::delete](http://skade.github.io/leveldb/leveldb/database/kv/trait.KV.html#tymethod.delete)
    fn delete(
        db: &Database<EncodedKey<Self>>,
        sync: bool,
        key: &EncodedKey<Self>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        db.delete(leveldb::options::WriteOptions { sync }, key)
            .map_err(|e| e.into())
    }
}

impl<'a, T: KeyOrm<'a> + Serialize + DeserializeOwned> KVOrm<'a> for T {}