use std::any::TypeId;
use crate::handle::{HandleId, UntypedHandle};
#[derive(Debug, Clone)]
pub enum AssetEvent {
Created {
handle: UntypedHandle,
type_id: TypeId,
version: u32,
},
Modified {
handle: UntypedHandle,
type_id: TypeId,
version: u32,
},
Removed {
handle_id: HandleId,
type_id: TypeId,
},
LoadFailed {
handle: UntypedHandle,
type_id: TypeId,
error: String,
},
}
impl AssetEvent {
pub fn type_id(&self) -> TypeId {
match self {
AssetEvent::Created { type_id, .. } => *type_id,
AssetEvent::Modified { type_id, .. } => *type_id,
AssetEvent::Removed { type_id, .. } => *type_id,
AssetEvent::LoadFailed { type_id, .. } => *type_id,
}
}
pub fn handle_id(&self) -> HandleId {
match self {
AssetEvent::Created { handle, .. } => handle.id(),
AssetEvent::Modified { handle, .. } => handle.id(),
AssetEvent::Removed { handle_id, .. } => *handle_id,
AssetEvent::LoadFailed { handle, .. } => handle.id(),
}
}
pub fn is_created(&self) -> bool {
matches!(self, AssetEvent::Created { .. })
}
pub fn is_modified(&self) -> bool {
matches!(self, AssetEvent::Modified { .. })
}
pub fn is_removed(&self) -> bool {
matches!(self, AssetEvent::Removed { .. })
}
pub fn is_failed(&self) -> bool {
matches!(self, AssetEvent::LoadFailed { .. })
}
}
#[derive(Debug, Default)]
pub struct AssetEventBuffer {
events: Vec<AssetEvent>,
}
impl AssetEventBuffer {
pub fn new() -> Self {
Self { events: Vec::new() }
}
pub fn push(&mut self, event: AssetEvent) {
self.events.push(event);
}
pub fn drain(&mut self) -> impl Iterator<Item = AssetEvent> + '_ {
self.events.drain(..)
}
pub fn iter(&self) -> impl Iterator<Item = &AssetEvent> {
self.events.iter()
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn clear(&mut self) {
self.events.clear();
}
}
pub struct TypedEventFilter<T> {
type_id: TypeId,
_marker: std::marker::PhantomData<T>,
}
impl<T: 'static> TypedEventFilter<T> {
pub fn new() -> Self {
Self {
type_id: TypeId::of::<T>(),
_marker: std::marker::PhantomData,
}
}
pub fn matches(&self, event: &AssetEvent) -> bool {
event.type_id() == self.type_id
}
pub fn filter<'a>(
&self,
events: impl Iterator<Item = &'a AssetEvent>,
) -> impl Iterator<Item = &'a AssetEvent> {
let type_id = self.type_id;
events.filter(move |e| e.type_id() == type_id)
}
}
impl<T: 'static> Default for TypedEventFilter<T> {
fn default() -> Self {
Self::new()
}
}