minecraft_assets/api/resource/path.rs
1use std::{
2 ops::{Deref, DerefMut},
3 path::{Path, PathBuf},
4};
5
6use crate::api::{ResourceKind, ResourceLocation};
7
8/// Represents the full path to a resource, e.g., on the local file system.
9pub struct ResourcePath(PathBuf);
10
11impl ResourcePath {
12 /// Returns the full path to the given resource.
13 ///
14 /// The `root` argument should be the path to the directory containing the
15 /// `assets/` and (optionally) `data/` directories.
16 ///
17 /// **NOTE:** no validation of the path is performed. The returned path may
18 /// not point to an existing file. This method simply computes what the path
19 /// should be for a given resource.
20 pub fn for_resource(root: impl AsRef<Path>, resource: &ResourceLocation) -> Self {
21 let mut path = Self::for_kind(root, resource.namespace(), resource.kind());
22
23 path.push(resource.path());
24
25 Self(path.with_extension(resource.kind().extension()))
26 }
27
28 /// Returns the full path to the directory that contains resources of the
29 /// given type for the given namespace.
30 ///
31 /// The `root` argument should be the path to the directory containing the
32 /// `assets/` and (optionally) `data/` directories.
33 ///
34 /// **NOTE:** no validation of the path is performed. The returned path may
35 /// not point to an existing directory. This method simply computes what the
36 /// path should be for a given resource type.
37 pub fn for_kind(root: impl AsRef<Path>, namespace: &str, kind: ResourceKind) -> Self {
38 let mut path = PathBuf::from(root.as_ref());
39
40 // `assets/` or `data/`.
41 path.push(kind.category().directory());
42 path.push(namespace);
43 path.push(kind.directory());
44
45 Self(path)
46 }
47
48 /// Consumes `self` and returns the inner [`PathBuf`].
49 pub fn into_inner(self) -> PathBuf {
50 self.0
51 }
52}
53
54impl AsRef<Path> for ResourcePath {
55 fn as_ref(&self) -> &Path {
56 self.0.as_ref()
57 }
58}
59
60impl Deref for ResourcePath {
61 type Target = PathBuf;
62
63 fn deref(&self) -> &Self::Target {
64 &self.0
65 }
66}
67
68impl DerefMut for ResourcePath {
69 fn deref_mut(&mut self) -> &mut Self::Target {
70 &mut self.0
71 }
72}