godot_core/meta/
object_to_owned.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
8use crate::obj::{Gd, GodotClass, WithBaseField};
9
10/// Obtain owned `Gd` from either `&self` or `&Gd`.
11///
12/// This trait allows passing either `Gd<T>` or `C` (where `C: WithBaseField`) to functions that need an owned `Gd<T>`.
13///
14/// This is primarily used for signal connection methods in [`TypedSignal`][crate::registry::signal::TypedSignal] and
15/// [`ConnectBuilder`][crate::registry::signal::ConnectBuilder], where you can pass either a `&Gd` (outside) or `&SomeClass`
16/// (from within `impl` block) as the receiver object.
17///
18/// # Similar traits
19/// - [`UniformObjectDeref`][crate::meta::UniformObjectDeref] provides unified dereferencing of user and engine classes.
20/// - [`AsArg`][crate::meta::AsArg] enables general argument conversions for Godot APIs.
21pub trait ObjectToOwned<T: GodotClass> {
22    /// Converts the object reference to an owned `Gd<T>`.
23    fn object_to_owned(&self) -> Gd<T>;
24}
25
26impl<T: GodotClass> ObjectToOwned<T> for Gd<T> {
27    fn object_to_owned(&self) -> Gd<T> {
28        self.clone()
29    }
30}
31
32impl<C: WithBaseField> ObjectToOwned<C> for C {
33    fn object_to_owned(&self) -> Gd<C> {
34        WithBaseField::to_gd(self)
35    }
36}