bevy_feathers/
handle_or_path.rs

1//! Provides a way to specify assets either by handle or by path.
2use bevy_asset::{Asset, Handle};
3use bevy_reflect::Reflect;
4
5/// Enum that represents a reference to an asset as either a [`Handle`] or a [`String`] path.
6///
7/// This is useful for when you want to specify an asset, but don't always have convenient
8/// access to an asset server reference.
9#[derive(Clone, Debug, Reflect)]
10pub enum HandleOrPath<T: Asset> {
11    /// Specify the asset reference as a handle.
12    Handle(Handle<T>),
13    /// Specify the asset reference as a [`String`].
14    Path(String),
15}
16
17impl<T: Asset> Default for HandleOrPath<T> {
18    fn default() -> Self {
19        Self::Path("".to_string())
20    }
21}
22
23// Necessary because we don't want to require T: PartialEq
24impl<T: Asset> PartialEq for HandleOrPath<T> {
25    fn eq(&self, other: &Self) -> bool {
26        match (self, other) {
27            (HandleOrPath::Handle(h1), HandleOrPath::Handle(h2)) => h1 == h2,
28            (HandleOrPath::Path(p1), HandleOrPath::Path(p2)) => p1 == p2,
29            _ => false,
30        }
31    }
32}
33
34impl<T: Asset> From<Handle<T>> for HandleOrPath<T> {
35    fn from(h: Handle<T>) -> Self {
36        HandleOrPath::Handle(h)
37    }
38}
39
40impl<T: Asset> From<&str> for HandleOrPath<T> {
41    fn from(p: &str) -> Self {
42        HandleOrPath::Path(p.to_string())
43    }
44}
45
46impl<T: Asset> From<String> for HandleOrPath<T> {
47    fn from(p: String) -> Self {
48        HandleOrPath::Path(p.clone())
49    }
50}
51
52impl<T: Asset> From<&String> for HandleOrPath<T> {
53    fn from(p: &String) -> Self {
54        HandleOrPath::Path(p.to_string())
55    }
56}
57
58impl<T: Asset + Clone> From<&HandleOrPath<T>> for HandleOrPath<T> {
59    fn from(p: &HandleOrPath<T>) -> Self {
60        p.to_owned()
61    }
62}