#[allow(dead_code)]
use bitte::bitte;
#[bitte]
trait AsyncRepository {
async fn find_by_id(&self, id: u64) -> Option<String>;
async fn save(&mut self, data: String) -> Result<u64, String>;
async fn delete(&mut self, id: u64) -> Result<(), String>;
fn cache_size(&self) -> usize;
}
#[bitte(Send, Sync)]
trait AsyncService {
async fn process(&self, input: Vec<u8>) -> Result<Vec<u8>, Box<dyn std::error::Error>>;
}
trait AsyncMixedTrait {
#[bitte]
async fn default_bounds(&self) -> String;
#[bitte(?Send)]
async fn no_send(&self) -> String;
#[bitte(?Sync)]
async fn no_sync(&self) -> String;
#[bitte(?Send, ?Sync)]
async fn no_bounds(&self) -> String;
async fn still_async(&self) -> String;
}
struct InMemoryRepo {
data: std::collections::HashMap<u64, String>,
}
#[bitte]
impl AsyncRepository for InMemoryRepo {
async fn find_by_id(&self, id: u64) -> Option<String> {
self.data.get(&id).cloned()
}
async fn save(&mut self, data: String) -> Result<u64, String> {
let id = rand::random::<u64>();
self.data.insert(id, data);
Ok(id)
}
async fn delete(&mut self, id: u64) -> Result<(), String> {
self.data.remove(&id);
Ok(())
}
fn cache_size(&self) -> usize {
self.data.len()
}
}
struct FileRepo {
path: std::path::PathBuf,
}
impl AsyncRepository for FileRepo {
fn find_by_id(&self, id: u64) -> impl std::future::Future<Output = Option<String>> {
async move {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
Some(format!("Data for id {}", id))
}
}
fn save(&mut self, _data: String) -> impl std::future::Future<Output = Result<u64, String>> {
async move {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
Ok(rand::random::<u64>())
}
}
fn delete(&mut self, _id: u64) -> impl std::future::Future<Output = Result<(), String>> {
async move {
tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
Ok(())
}
}
fn cache_size(&self) -> usize {
0 }
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut repo = InMemoryRepo {
data: std::collections::HashMap::new(),
};
let id = repo.save("Hello, bitte!".to_string()).await?;
println!("Saved data with id: {}", id);
if let Some(data) = repo.find_by_id(id).await {
println!("Found data: {}", data);
}
println!("Cache size: {}", repo.cache_size());
repo.delete(id).await?;
println!("Data deleted");
Ok(())
}