You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4 KiB

4 years ago
  1. extern crate rusty_leveldb;
  2. use self::rusty_leveldb::DB;
  3. use super::constants;
  4. pub struct Db {
  5. storage: DB,
  6. }
  7. impl Db {
  8. pub fn new(path: String, in_memory: bool) -> Db {
  9. let opt: rusty_leveldb::Options;
  10. if in_memory {
  11. opt = rusty_leveldb::in_memory();
  12. } else {
  13. opt = Default::default();
  14. }
  15. let database = DB::open(path, opt).unwrap();
  16. Db { storage: database }
  17. }
  18. pub fn insert(&mut self, k: [u8; 32], t: u8, il: u32, b: Vec<u8>) {
  19. let mut v: Vec<u8>;
  20. v = [t].to_vec();
  21. let il_bytes = il.to_le_bytes();
  22. v.extend(il_bytes.to_vec()); // il_bytes are [u8;4] (4 bytes)
  23. v.extend(&b);
  24. self.storage.put(&k[..], &v[..]).unwrap();
  25. }
  26. pub fn get(&mut self, k: &[u8; 32]) -> (u8, u32, Vec<u8>) {
  27. if k.to_vec() == constants::EMPTYNODEVALUE.to_vec() {
  28. return (0, 0, constants::EMPTYNODEVALUE.to_vec());
  29. }
  30. match self.storage.get(k) {
  31. Some(x) => {
  32. let t = x[0];
  33. let il_bytes: [u8; 4] = [x[1], x[2], x[3], x[4]];
  34. let il = u32::from_le_bytes(il_bytes);
  35. let b = &x[5..];
  36. (t, il, b.to_vec())
  37. }
  38. None => (
  39. constants::TYPENODEEMPTY,
  40. 0,
  41. constants::EMPTYNODEVALUE.to_vec(),
  42. ),
  43. }
  44. }
  45. }