use indexmap::IndexMap;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use vantage_types::Record;
pub mod dataset_insertable;
pub mod dataset_readable;
pub mod dataset_writable;
pub mod im_table;
pub mod valueset_insertable;
pub mod valueset_readable;
pub mod valueset_writable;
pub use im_table::ImTable;
type TableStorage<V> = Arc<Mutex<HashMap<String, IndexMap<String, Record<V>>>>>;
#[derive(Debug)]
pub struct ImDataSource<V = serde_json::Value> {
tables: TableStorage<V>,
}
impl<V> Clone for ImDataSource<V> {
fn clone(&self) -> Self {
Self {
tables: self.tables.clone(),
}
}
}
impl<V> ImDataSource<V> {
pub fn new() -> Self {
Self {
tables: Arc::new(Mutex::new(HashMap::new())),
}
}
}
impl<V: Clone> ImDataSource<V> {
pub(super) fn with_table<R>(
&self,
table_name: &str,
f: impl FnOnce(&IndexMap<String, Record<V>>) -> R,
) -> R {
let tables = self.tables.lock().unwrap();
match tables.get(table_name) {
Some(table) => f(table),
None => f(&IndexMap::new()),
}
}
pub fn table_len(&self, table_name: &str) -> usize {
self.with_table(table_name, |table| table.len())
}
pub(super) fn with_table_mut<R>(
&self,
table_name: &str,
f: impl FnOnce(&mut IndexMap<String, Record<V>>) -> R,
) -> R {
let mut tables = self.tables.lock().unwrap();
let table = tables.entry(table_name.to_string()).or_default();
f(table)
}
}
impl<V> Default for ImDataSource<V> {
fn default() -> Self {
Self::new()
}
}