use std::sync::Arc;
use crate::asset::{AssetKey, PendingAsset};
use crate::QueryError;
pub struct AssetLoadingState<K: AssetKey> {
value: Option<Arc<K::Asset>>,
key: K,
}
impl<K: AssetKey> AssetLoadingState<K> {
pub fn loading(key: K) -> Self {
Self { value: None, key }
}
pub fn ready(key: K, value: Arc<K::Asset>) -> Self {
Self {
value: Some(value),
key,
}
}
pub fn is_loading(&self) -> bool {
self.value.is_none()
}
pub fn is_ready(&self) -> bool {
self.value.is_some()
}
pub fn get(&self) -> Option<&Arc<K::Asset>> {
self.value.as_ref()
}
pub fn into_inner(self) -> Option<Arc<K::Asset>> {
self.value
}
pub fn suspend(self) -> Result<Arc<K::Asset>, QueryError> {
match self.value {
None => Err(QueryError::Suspend {
asset: PendingAsset::new(self.key),
}),
Some(v) => Ok(v),
}
}
pub fn key(&self) -> &K {
&self.key
}
}
impl<K: AssetKey> std::fmt::Debug for AssetLoadingState<K>
where
K::Asset: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.value {
None => write!(f, "AssetLoadingState::Loading({:?})", self.key),
Some(v) => write!(f, "AssetLoadingState::Ready({:?}, {:?})", self.key, v),
}
}
}