swiftide_core/search_strategies/
custom_strategy.rsuse crate::querying::{self, states, Query};
use anyhow::{anyhow, Result};
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
type QueryGenerator<Q> = Arc<dyn Fn(&Query<states::Pending>) -> Result<Q> + Send + Sync>;
type AsyncQueryGenerator<Q> = Arc<
dyn Fn(&Query<states::Pending>) -> Pin<Box<dyn Future<Output = Result<Q>> + Send>>
+ Send
+ Sync,
>;
pub struct CustomStrategy<Q> {
query: Option<QueryGenerator<Q>>,
async_query: Option<AsyncQueryGenerator<Q>>,
_marker: PhantomData<Q>,
}
impl<Q: Send + Sync + 'static> querying::SearchStrategy for CustomStrategy<Q> {}
impl<Q> Default for CustomStrategy<Q> {
fn default() -> Self {
Self {
query: None,
async_query: None,
_marker: PhantomData,
}
}
}
impl<Q> Clone for CustomStrategy<Q> {
fn clone(&self) -> Self {
Self {
query: self.query.clone(),
async_query: self.async_query.clone(),
_marker: PhantomData,
}
}
}
impl<Q: Send + Sync + 'static> CustomStrategy<Q> {
pub fn from_query(
query: impl Fn(&Query<states::Pending>) -> Result<Q> + Send + Sync + 'static,
) -> Self {
Self {
query: Some(Arc::new(query)),
async_query: None,
_marker: PhantomData,
}
}
pub fn from_async_query<F>(
query: impl Fn(&Query<states::Pending>) -> F + Send + Sync + 'static,
) -> Self
where
F: Future<Output = Result<Q>> + Send + 'static,
{
Self {
query: None,
async_query: Some(Arc::new(move |q| Box::pin(query(q)))),
_marker: PhantomData,
}
}
pub async fn build_query(&self, query_node: &Query<states::Pending>) -> Result<Q> {
match (&self.query, &self.async_query) {
(Some(query_fn), _) => query_fn(query_node),
(_, Some(async_fn)) => async_fn(query_node).await,
_ => Err(anyhow!("No query function has been set.")),
}
}
}