pub mod error; use async_std::sync::{Arc, RwLock}; use error::MTTError; use std::collections::HashMap; #[derive(Clone)] pub struct MoreThanText { tables: Arc>>, } impl MoreThanText { pub async fn new() -> Self { Self { tables: Arc::new(RwLock::new(HashMap::new())), } } pub async fn new_table(&self, name: &str) -> Result { let mut tables = self.tables.write().await; match tables.get(name) { Some(_) => Err(MTTError::new(format!("table {} already exists", name))), None => { tables.insert(name.to_string(), Table::new().await); Ok(Table::new().await) } } } } pub struct Table; impl Table { pub async fn new() -> Self { Self {} } } #[cfg(test)] mod database { use super::*; #[async_std::test] async fn create_table() { let db = MoreThanText::new().await; db.new_table("william").await.unwrap(); } #[async_std::test] async fn table_names_are_unique() -> Result<(), String> { let db = MoreThanText::new().await; let name = "alexandar"; let msg = format!("table {} already exists", name); db.new_table(name).await.unwrap(); match db.new_table(name).await { Ok(_) => Err("Duplicate table names are not allowed.".to_string()), Err(err) => { if err.to_string() == msg { Ok(()) } else { Err(format!( "Error message is incorrect: Got: '{}' Want: '{}'", err.to_string(), msg )) } } } } } #[cfg(test)] mod table { use super::*; #[async_std::test] async fn create() { Table::new().await; } }