最近準備用Rust寫一個完善的blockchain的教學demo,在持久化時考慮到使用leveldb。透過查閱文件,發現Rust中已經提供了使用leveldb的介面。將官方的例子修改了下,能夠執行透過。
- 原始碼
//src/main.rs
use std::{env, fs};
use leveldb::database::Database;
use leveldb::iterator::Iterable;
use leveldb::kv::KV;
use leveldb::options::{Options,WriteOptions,ReadOptions};
fn main() {
let mut dir = env::current_dir().unwrap();
dir.push("demo");
let path_buf = dir.clone();
fs::create_dir_all(dir).unwrap();
let path = path_buf.as_path();
let mut options = Options::new();
options.create_if_missing = true;
//建立資料庫
let database = match Database::open(path, options) {
Ok(db) => { db },
Err(e) => { panic!("failed to open database: {:?}", e) }
};
//寫資料庫
let write_opts = WriteOptions::new();
match database.put(write_opts, 1, &[1]) {
Ok(_) => { () },
Err(e) => { panic!("failed to write to database: {:?}", e) }
};
//讀資料庫
let read_opts = ReadOptions::new();
let res = database.get(read_opts, 1);
match res {
Ok(data) => {
assert!(data.is_some());
assert_eq!(data, Some(vec![1]));
}
Err(e) => { panic!("failed reading data: {:?}", e) }
}
let read_opts = ReadOptions::new();
let mut iter = database.iter(read_opts);
let entry = iter.next();
assert_eq!(
entry,
Some((1, vec![1]))
);
}
- 配置檔案
//配置檔案Cargo.toml中新增如下
[dependencies]
leveldb = "0.8.5"
本作品採用《CC 協議》,轉載必須註明作者和本文連結