Struct gdnative::object::Ref

pub struct Ref<T, Own = Shared>
where T: GodotObject, Own: Ownership,
{ /* private fields */ }
Expand description

A polymorphic smart pointer for Godot objects whose behavior changes depending on the memory management method of the underlying type and the thread access status.

§Manually-managed types

Shared references to manually-managed types, like Ref<Node, Shared>, act like raw pointers. They are safe to alias, can be sent between threads, and can also be taken as method arguments (converted from Variant). They can’t be used directly. Instead, it’s required to obtain a safe view first. See the “Obtaining a safe view” section below for more information.

ThreadLocal references to manually-managed types cannot normally be obtained, since it does not add anything over Shared ones.

Unique references to manually-managed types, like Ref<Node, Unique>, can’t be aliased or sent between threads, but can be used safely. However, they won’t be automatically freed on drop, and are leaked if not passed to the engine or freed manually with free. Unique references can be obtained through constructors safely, or assume_unique in unsafe contexts.

§Reference-counted types

Shared references to reference-counted types, like Ref<Reference, Shared>, act like Arc smart pointers. New references can be created with Clone, and they can be sent between threads. The pointer is presumed to be always valid. As such, more operations are available even when thread safety is not assumed. However, API methods still can’t be used directly, and users are required to obtain a safe view first. See the “Obtaining a safe view” section below for more information.

ThreadLocal reference to reference-counted types, like Ref<Reference, ThreadLocal>, add the ability to call API methods safely. Unlike Unique references, it’s unsafe to convert them to Shared because there might be other ThreadLocal references in existence.

§Obtaining a safe view

In a lot of cases, references obtained from the engine as return values or arguments aren’t safe to use, due to lack of pointer validity and thread safety guarantees in the API. As such, it’s usually required to use unsafe code to obtain safe views of the same object before API methods can be called. The ways to cast between different reference types are as follows:

FromToMethodNote
Unique&'a TDeref (API methods can be called directly) / as_ref-
ThreadLocal&'a TDeref (API methods can be called directly) / as_refOnly if T is a reference-counted type.
Shared&'a Tunsafe assume_safe::<'a>The underlying object must be valid, and exclusive to this thread during 'a.
UniqueThreadLocalinto_thread_local-
UniqueSharedinto_shared-
SharedThreadLocalunsafe assume_thread_localThe reference must be local to the current thread.
Shared / ThreadLocalUniqueunsafe assume_uniqueThe reference must be unique.
ThreadLocalSharedunsafe assume_unique().into_shared()The reference must be unique.

§Using as method arguments or return values

In order to enforce thread safety statically, the ability to be passed to the engine is only given to some reference types. Specifically, they are:

  • All owned Ref<T, Unique> references. The Unique access is lost if passed into a method.
  • Owned and borrowed Shared references, including temporary ones (TRef).

It’s unsound to pass ThreadLocal references to the engine because there is no guarantee that the reference will stay on the same thread.

§Conditional trait implementations

Many trait implementations for Ref are conditional, dependent on the type parameters. When viewing rustdoc documentation, you may expand the documentation on their respective impl blocks for more detailed explanations of the trait bounds.

Implementations§

§

impl<T> Ref<T, Unique>

pub fn new() -> Ref<T, Unique>

Creates a new instance of T.

The lifetime of the returned object is not automatically managed if T is a manually- managed type.

§

impl<T> Ref<T, Unique>
where T: GodotObject,

pub fn by_class_name(class_name: &str) -> Option<Ref<T, Unique>>

Creates a new instance of a sub-class of T by its class name. Returns None if the class does not exist, cannot be constructed, has a different Memory from, or is not a sub-class of T.

The lifetime of the returned object is not automatically managed if T is a manually- managed type. This means that if Object is used as the type parameter, any Reference objects created, if returned, will be leaked. As a result, such calls will return None. Casting between Object and Reference is possible on TRef and bare references.

§

impl<T, Own> Ref<T, Own>

Method for references that can be safely used.

pub fn as_ref(&self) -> TRef<'_, T, Own>

Returns a safe temporary reference that tracks thread access.

Ref<T, Own> can be safely dereferenced if either:

  • T is reference-counted and Ownership is not Shared,
  • or, T is manually-managed and Ownership is Unique.
§

impl<T, Own> Ref<T, Own>

Methods for references that point to valid objects, but are not necessarily safe to use.

  • All Refs to reference-counted types always point to valid objects.
  • Ref to manually-managed types are only guaranteed to be valid if Unique.

pub fn cast<U>(self) -> Option<Ref<U, Own>>
where U: GodotObject<Memory = <T as GodotObject>::Memory> + SubClass<T>,

Performs a dynamic reference cast to target type, keeping the reference count. Shorthand for try_cast().ok().

The cast method can only be used for downcasts. For statically casting to a supertype, use upcast instead.

This is only possible between types with the same Memorys, since otherwise the reference can get leaked. Casting between Object and Reference is possible on TRef and bare references.

pub fn upcast<U>(self) -> Ref<U, Own>
where U: GodotObject<Memory = <T as GodotObject>::Memory>, T: SubClass<U>,

Performs a static reference upcast to a supertype, keeping the reference count. This is guaranteed to be valid.

This is only possible between types with the same Memorys, since otherwise the reference can get leaked. Casting between Object and Reference is possible on TRef and bare references.

pub fn try_cast<U>(self) -> Result<Ref<U, Own>, Ref<T, Own>>
where U: GodotObject<Memory = <T as GodotObject>::Memory> + SubClass<T>,

Performs a dynamic reference cast to target type, keeping the reference count.

This is only possible between types with the same Memorys, since otherwise the reference can get leaked. Casting between Object and Reference is possible on TRef and bare references.

§Errors

Returns Err(self) if the cast failed.

pub fn cast_instance<C>(self) -> Option<Instance<C, Own>>
where C: NativeClass<Base = T>,

Performs a downcast to a NativeClass instance, keeping the reference count. Shorthand for try_cast_instance().ok().

The resulting Instance is not necessarily safe to use directly.

pub fn try_cast_instance<C>(self) -> Result<Instance<C, Own>, Ref<T, Own>>
where C: NativeClass<Base = T>,

Performs a downcast to a NativeClass instance, keeping the reference count.

§Errors

Returns Err(self) if the cast failed.

§

impl<T> Ref<T>
where T: GodotObject,

Methods for references that can’t be used directly, and have to be assumed safe unsafely.

pub unsafe fn assume_safe<'a, 'r>(&'r self) -> TRef<'a, T>
where AssumeSafeLifetime<'a, 'r>: LifetimeConstraint<<T as GodotObject>::Memory>,

Assume that self is safe to use, returning a reference that can be used to call API methods.

This is guaranteed to be a no-op at runtime if debug_assertions is disabled. Runtime sanity checks may be added in debug builds to help catch bugs.

§Safety

Suppose that the lifetime of the returned reference is 'a. It’s safe to call assume_safe only if:

  1. During the entirety of 'a, the underlying object will always be valid.

    This is always true for reference-counted types. For them, the 'a lifetime will be constrained to the lifetime of &self.

    This means that any methods called on the resulting reference will not free it, unless it’s the last operation within the lifetime.

    If any script methods are called, the code ran as a consequence will also not free it. This can happen via virtual method calls on other objects, or signals connected in a non-deferred way.

  2. During the entirety of ’a, the thread from which assume_safe is called has exclusive access to the underlying object.

    This is because all Godot objects have “interior mutability” in Rust parlance, and can’t be shared across threads. The best way to guarantee this is to follow the official thread-safety guidelines across the codebase.

Failure to satisfy either of the conditions will lead to undefined behavior.

pub unsafe fn assume_unique(self) -> Ref<T, Unique>

Assume that self is the unique reference to the underlying object.

This is guaranteed to be a no-op at runtime if debug_assertions is disabled. Runtime sanity checks may be added in debug builds to help catch bugs.

§Safety

Calling assume_unique when self isn’t the unique reference is instant undefined behavior. This is a much stronger assumption than assume_safe and should be used with care.

§

impl<T> Ref<T>
where T: GodotObject<Memory = ManuallyManaged>,

Extra methods with explicit sanity checks for manually-managed unsafe references.

pub unsafe fn is_instance_sane(&self) -> bool

Returns true if the pointer currently points to a valid object of the correct type. This does NOT guarantee that it’s safe to use this pointer.

§Safety

This thread must have exclusive access to the object during the call.

pub unsafe fn assume_safe_if_sane<'a>(&self) -> Option<TRef<'a, T>>

Assume that self is safe to use, if a sanity check using is_instance_sane passed.

§Safety

The same safety constraints as assume_safe applies. The sanity check does NOT guarantee that the operation is safe.

pub unsafe fn assume_unique_if_sane(self) -> Option<Ref<T, Unique>>

Assume that self is the unique reference to the underlying object, if a sanity check using is_instance_sane passed.

§Safety

Calling assume_unique_if_sane when self isn’t the unique reference is instant undefined behavior. This is a much stronger assumption than assume_safe and should be used with care.

§

impl<T> Ref<T>
where T: GodotObject<Memory = RefCounted>,

Methods for conversion from Shared to ThreadLocal access. This is only available for reference-counted types.

pub unsafe fn assume_thread_local(self) -> Ref<T, ThreadLocal>

Assume that all references to the underlying object is local to the current thread.

This is guaranteed to be a no-op at runtime.

§Safety

Calling assume_thread_local when there are references on other threads is instant undefined behavior. This is a much stronger assumption than assume_safe and should be used with care.

§

impl<T> Ref<T, Unique>
where T: GodotObject<Memory = RefCounted>,

Methods for conversion from Unique to ThreadLocal access. This is only available for reference-counted types.

pub fn into_thread_local(self) -> Ref<T, ThreadLocal>

Convert to a thread-local reference.

This is guaranteed to be a no-op at runtime.

§

impl<T> Ref<T, Unique>
where T: GodotObject,

Methods for conversion from Unique to Shared access.

pub fn into_shared(self) -> Ref<T>

Convert to a shared reference.

This is guaranteed to be a no-op at runtime.

§

impl<T> Ref<T, Unique>
where T: GodotObject<Memory = ManuallyManaged>,

Methods for freeing Unique references to manually-managed objects.

pub fn free(self)

Manually frees the object.

Manually-managed objects are not free-on-drop even when the access is unique, because it’s impossible to know whether methods take “ownership” of them or not. It’s up to the user to decide when they should be freed.

This is only available for Unique references. If you have a Ref with another access, and you are sure that it is unique, use assume_unique to convert it to a Unique one.

§

impl<T> Ref<T, Unique>
where T: GodotObject<Memory = ManuallyManaged> + QueueFree,

Methods for freeing Unique references to manually-managed objects.

pub fn queue_free(self)

Queues the object for deallocation in the near future. This is preferable for Nodes compared to Ref::free.

This is only available for Unique references. If you have a Ref with another access, and you are sure that it is unique, use assume_unique to convert it to a Unique one.

Trait Implementations§

§

impl<'a, T> AsVariant for &'a Ref<T>
where T: GodotObject,

§

type Target = T

§

impl<T> AsVariant for Ref<T>
where T: GodotObject,

§

type Target = T

§

impl<T> AsVariant for Ref<T, Unique>
where T: GodotObject,

§

type Target = T

§

impl<T, Own> Borrow<T> for Ref<T, Own>

Ref<T, Own> can be safely dereferenced if either:

  • T is reference-counted and Ownership is not Shared,
  • or, T is manually-managed and Ownership is Unique.
§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T, Own> Clone for Ref<T, Own>

Ref is Clone if the access is not Unique.

§

fn clone(&self) -> Ref<T, Own>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl<T, Own> Debug for Ref<T, Own>
where T: GodotObject, Own: Ownership,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T, Own> Deref for Ref<T, Own>

Ref<T, Own> can be safely dereferenced if either:

  • T is reference-counted and Ownership is not Shared,
  • or, T is manually-managed and Ownership is Unique.
§

type Target = T

The resulting type after dereferencing.
§

fn deref(&self) -> &<Ref<T, Own> as Deref>::Target

Dereferences the value.
§

impl<T> Export for Ref<T>
where T: GodotObject,

§

type Hint = NoHint

A type-specific hint type that is valid for the type being exported. Read more
§

fn export_info(_hint: Option<<Ref<T> as Export>::Hint>) -> ExportInfo

Returns ExportInfo given an optional typed hint.
§

impl<T> FromVariant for Ref<T>
where T: GodotObject,

§

impl<T, Own> Hash for Ref<T, Own>
where T: GodotObject, Own: Ownership,

Hashes the raw pointer.

§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
§

impl<T, Own> Ord for Ref<T, Own>
where T: GodotObject, Own: Ownership,

Ordering of the raw pointer value.

§

fn cmp(&self, other: &Ref<T, Own>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
§

impl<T> OwnedToVariant for Ref<T, Unique>
where T: GodotObject,

§

impl<T, Own, RhsOws> PartialEq<Ref<T, RhsOws>> for Ref<T, Own>
where T: GodotObject, Own: Ownership, RhsOws: Ownership,

Reference equality.

§

fn eq(&self, other: &Ref<T, RhsOws>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<T, Own> PartialOrd for Ref<T, Own>
where T: GodotObject, Own: Ownership,

Ordering of the raw pointer value.

§

fn partial_cmp(&self, other: &Ref<T, Own>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
§

impl<T> ToVariant for Ref<T>
where T: GodotObject,

§

fn to_variant(&self) -> Variant

§

impl<'a, T, U> AsArg<U> for &'a Ref<T>
where T: GodotObject + SubClass<U>, U: GodotObject,

§

impl<T, U> AsArg<U> for Ref<T>
where T: GodotObject + SubClass<U>, U: GodotObject,

§

impl<T, U> AsArg<U> for Ref<T, Unique>
where T: GodotObject + SubClass<U>, U: GodotObject,

§

impl<T, Own> Copy for Ref<T, Own>

Ref is Copy if the underlying object is manually-managed, and the access is not Unique.

§

impl<T, Own> Eq for Ref<T, Own>
where T: GodotObject, Own: Ownership,

Reference equality.

§

impl<T, Own> Send for Ref<T, Own>
where T: GodotObject, Own: Ownership + Send,

Ref is Send if the thread access is Shared or Unique.

§

impl<T, Own> Sync for Ref<T, Own>
where T: GodotObject, Own: Ownership + Sync,

Ref is Sync if the thread access is Shared.

Auto Trait Implementations§

§

impl<T, Own> Freeze for Ref<T, Own>

§

impl<T, Own> RefUnwindSafe for Ref<T, Own>

§

impl<T, Own> Unpin for Ref<T, Own>
where <<T as GodotObject>::Memory as MemorySpec>::PtrWrapper: Unpin, Own: Unpin,

§

impl<T, Own> UnwindSafe for Ref<T, Own>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> OwnedToVariant for T
where T: ToVariant,

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.