Skip to main content

godot_core/classes/
manual_extensions.rs

1/*
2 * Copyright (c) godot-rust; Bromeon and contributors.
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 */
7
8//! Adds new convenience APIs to existing classes.
9//!
10//! This should not add new functionality, but provide existing one in a slightly nicer way to use. Generally, we should be conservative
11//! about adding methods here, as it's a potentially endless quest, and many are better suited in high-level APIs or third-party crates.
12//!
13//! See also sister module [super::type_safe_replacements].
14
15use crate::builtin::NodePath;
16use crate::classes::{Node, PackedScene};
17use crate::global::Error;
18use crate::meta::{AsArg, arg_into_ref};
19use crate::obj::{Gd, Inherits};
20
21/// Manual extensions for the `Node` class.
22impl Node {
23    /// ⚠️ Retrieves the node at path `path`, panicking if not found or bad type.
24    ///
25    /// # Panics
26    /// If the node is not found, or if it does not have type `T` or inherited.
27    pub fn get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Gd<T>
28    where
29        T: Inherits<Node>,
30    {
31        arg_into_ref!(path);
32
33        self.try_get_node_as(path).unwrap_or_else(|| {
34            panic!(
35                "There is no node of type {ty} at path `{path}`",
36                ty = T::class_id()
37            )
38        })
39    }
40
41    /// Retrieves the node at path `path` (fallible).
42    ///
43    /// If the node is not found, or if it does not have type `T` or inherited,
44    /// `None` will be returned.
45    pub fn try_get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Option<Gd<T>>
46    where
47        T: Inherits<Node>,
48    {
49        arg_into_ref!(path);
50
51        // TODO differentiate errors (not found, bad type) with Result
52        self.get_node_or_null(path)
53            .and_then(|node| node.try_cast::<T>().ok())
54    }
55}
56
57// ----------------------------------------------------------------------------------------------------------------------------------------------
58
59/// Manual extensions for the `PackedScene` class.
60impl PackedScene {
61    /// ⚠️ Instantiates the scene as type `T`, panicking if not found or bad type.
62    ///
63    /// # Panics
64    /// If the scene is not type `T` or inherited.
65    pub fn instantiate_as<T>(&self) -> Gd<T>
66    where
67        T: Inherits<Node>,
68    {
69        self.try_instantiate_as::<T>()
70            .unwrap_or_else(|| panic!("Failed to instantiate {to}", to = T::class_id()))
71    }
72
73    /// Instantiates the scene as type `T` (fallible).
74    ///
75    /// If the scene is not type `T` or inherited.
76    pub fn try_instantiate_as<T>(&self) -> Option<Gd<T>>
77    where
78        T: Inherits<Node>,
79    {
80        self.instantiate().and_then(|gd| gd.try_cast::<T>().ok())
81    }
82}
83
84// ----------------------------------------------------------------------------------------------------------------------------------------------
85
86/// Manual extensions for the `global::Error` enum.
87impl Error {
88    /// Returns `Ok(())` for `Error::OK`, and `Err(self)` for any `Error::ERR_*`.
89    ///
90    /// This is a convenience method that may be used to convert this type into one that can be used with the try operator (`?`)
91    /// for easy short circuiting of Godot `Error`s.
92    ///
93    /// ```
94    /// use godot::global::Error;
95    ///
96    /// assert_eq!(Error::OK.into_result(), Ok(()));
97    /// assert_eq!(Error::FAILED.into_result(), Err(Error::FAILED));
98    /// ```
99    pub fn into_result(self) -> Result<(), Self> {
100        if self == Error::OK { Ok(()) } else { Err(self) }
101    }
102
103    /// Creates an `Error` from a `Result<(), Error>`.
104    ///
105    /// `Ok(())` becomes `Error::OK`, and `Err(e)` becomes `e` (even in the unusual case where `e == Error::OK`).
106    ///
107    /// ```
108    /// use godot::global::Error;
109    ///
110    /// assert_eq!(Error::from_result(Ok(())), Error::OK);
111    /// assert_eq!(Error::from_result(Err(Error::FAILED)), Error::FAILED);
112    /// ```
113    pub fn from_result(result: Result<(), Self>) -> Self {
114        match result {
115            Ok(()) => Error::OK,
116            Err(e) => e,
117        }
118    }
119}