2020-10-15 16:52:08 +00:00
|
|
|
use byteorder::LittleEndian;
|
|
|
|
use sled::{Db, IVec};
|
|
|
|
use thiserror::Error;
|
|
|
|
use zerocopy::byteorder::I32;
|
|
|
|
use zerocopy::{AsBytes, LayoutVerified};
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Database {
|
|
|
|
db: Db,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum DataError {
|
|
|
|
#[error("value does not exist for key: {0}")]
|
|
|
|
KeyDoesNotExist(String),
|
|
|
|
|
|
|
|
#[error("internal database error: {0}")]
|
|
|
|
InternalError(#[from] sled::Error),
|
|
|
|
}
|
|
|
|
|
|
|
|
fn to_key(room_id: &str, username: &str, variable_name: &str) -> Vec<u8> {
|
|
|
|
let mut key = vec![];
|
|
|
|
key.extend_from_slice(room_id.as_bytes());
|
|
|
|
key.extend_from_slice(username.as_bytes());
|
|
|
|
key.extend_from_slice(variable_name.as_bytes());
|
|
|
|
key
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Database {
|
|
|
|
pub fn new(db: &Db) -> Database {
|
|
|
|
Database { db: db.clone() }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get_user_variable(
|
|
|
|
&self,
|
|
|
|
room_id: &str,
|
|
|
|
username: &str,
|
|
|
|
variable_name: &str,
|
2020-10-16 12:40:25 +00:00
|
|
|
) -> Result<i32, DataError> {
|
2020-10-15 16:52:08 +00:00
|
|
|
let key = to_key(room_id, username, variable_name);
|
|
|
|
|
2020-10-16 12:40:25 +00:00
|
|
|
if let Some(raw_value) = self.db.get(&key)? {
|
2020-10-15 16:52:08 +00:00
|
|
|
let layout: LayoutVerified<&[u8], I32<LittleEndian>> =
|
|
|
|
LayoutVerified::new_unaligned(&*raw_value).expect("bytes do not fit schema");
|
|
|
|
|
|
|
|
let value: I32<LittleEndian> = *layout;
|
2020-10-16 12:40:25 +00:00
|
|
|
Ok(value.get())
|
2020-10-15 16:52:08 +00:00
|
|
|
} else {
|
2020-10-16 12:40:25 +00:00
|
|
|
Err(DataError::KeyDoesNotExist(String::from_utf8(key).unwrap()))
|
2020-10-15 16:52:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn set_user_variable(
|
|
|
|
&self,
|
|
|
|
room_id: &str,
|
|
|
|
username: &str,
|
|
|
|
variable_name: &str,
|
|
|
|
value: i32,
|
|
|
|
) -> Result<(), DataError> {
|
|
|
|
let key = to_key(room_id, username, variable_name);
|
|
|
|
let db_value: I32<LittleEndian> = I32::new(value);
|
2020-10-16 12:40:25 +00:00
|
|
|
self.db.insert(&key, IVec::from(db_value.as_bytes()))?;
|
2020-10-15 16:52:08 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn delete_user_variable(
|
|
|
|
&self,
|
|
|
|
room_id: &str,
|
|
|
|
username: &str,
|
|
|
|
variable_name: &str,
|
|
|
|
) -> Result<(), DataError> {
|
|
|
|
let key = to_key(room_id, username, variable_name);
|
2020-10-16 12:40:25 +00:00
|
|
|
if let Some(_) = self.db.remove(&key)? {
|
2020-10-15 16:52:08 +00:00
|
|
|
Ok(())
|
|
|
|
} else {
|
2020-10-16 12:40:25 +00:00
|
|
|
Err(DataError::KeyDoesNotExist(String::from_utf8(key).unwrap()))
|
2020-10-15 16:52:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|