godot_core/obj/instance_id.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 std::fmt::{Debug, Display, Formatter, Result as FmtResult};
9use std::num::NonZeroU64;
10
11use crate::meta::error::{ConvertError, FromGodotError};
12use crate::meta::{FromGodot, GodotConvert, ToGodot};
13
14/// Represents a non-zero instance ID.
15///
16/// This is its own type for type safety and to deal with the inconsistent representation in Godot as both `u64` (C++) and `i64` (GDScript).
17/// You can usually treat this as an opaque value and pass it to and from GDScript; there are conversion methods however.
18#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
19#[repr(transparent)]
20pub struct InstanceId {
21 // Note: in the public API, signed i64 is the canonical representation.
22 //
23 // Methods converting to/from u64 exist only because GDExtension tends to work with u64. However, user-facing APIs
24 // interact with GDScript, which uses i64. Not having two representations avoids confusion about negative values.
25 value: NonZeroU64,
26}
27
28impl InstanceId {
29 /// Constructs an instance ID from an integer, or `None` if the integer is zero.
30 ///
31 /// This does *not* check if the instance is valid.
32 pub fn try_from_i64(id: i64) -> Option<Self> {
33 Self::try_from_u64(id as u64)
34 }
35
36 /// ⚠️ Constructs an instance ID from a non-zero integer, or panics.
37 ///
38 /// This does *not* check if the instance is valid.
39 ///
40 /// # Panics
41 /// If `id` is zero. Use [`try_from_i64`][Self::try_from_i64] if you are unsure.
42 pub fn from_i64(id: i64) -> Self {
43 Self::try_from_i64(id).expect("expected non-zero instance ID")
44 }
45
46 // Private: see rationale above
47 pub(crate) fn try_from_u64(id: u64) -> Option<Self> {
48 NonZeroU64::new(id).map(|value| Self { value })
49 }
50
51 pub fn to_i64(self) -> i64 {
52 self.to_u64() as i64
53 }
54
55 /// Returns if the obj being referred-to is inheriting `RefCounted`.
56 ///
57 /// This is a very fast operation and involves no engine round-trip, as the information is encoded in the ID itself.
58 pub fn is_ref_counted(self) -> bool {
59 self.to_u64() & (1u64 << 63) != 0
60 }
61
62 /// Dynamically checks if the instance behind the ID exists.
63 ///
64 /// Rather slow, involves engine round-trip plus object DB lookup. If you need the object, use
65 /// [`Gd::from_instance_id()`][crate::obj::Gd::from_instance_id] instead.
66 ///
67 /// This corresponds to Godot's global function `is_instance_id_valid()`.
68 #[doc(alias = "is_instance_id_valid")]
69 pub fn lookup_validity(self) -> bool {
70 crate::global::is_instance_id_valid(self.to_i64())
71 }
72
73 // Private: see rationale above
74 pub(crate) fn to_u64(self) -> u64 {
75 self.value.get()
76 }
77}
78
79impl Display for InstanceId {
80 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
81 write!(f, "{}", self.to_i64())
82 }
83}
84
85impl Debug for InstanceId {
86 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
87 write!(f, "InstanceId({})", self.to_i64())
88 }
89}
90
91impl GodotConvert for InstanceId {
92 // Use i64 and not u64 because the former can be represented in Variant, and is also the number format GDScript uses.
93 // The engine's C++ code can still use u64.
94 type Via = i64;
95}
96
97impl ToGodot for InstanceId {
98 type ToVia<'v> = i64;
99
100 fn to_godot(&self) -> Self::ToVia<'_> {
101 self.to_i64()
102 }
103}
104
105impl FromGodot for InstanceId {
106 fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
107 Self::try_from_i64(via).ok_or_else(|| FromGodotError::ZeroInstanceId.into_error(via))
108 }
109}