-
Notifications
You must be signed in to change notification settings - Fork 208
/
variant.rs
2057 lines (1840 loc) · 68 KB
/
variant.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::*;
use std::default::Default;
use std::fmt;
use std::mem::{forget, transmute};
use std::ptr;
use crate::core_types::*;
use crate::object::*;
use crate::private::{get_api, ManuallyManagedClassPlaceholder};
use crate::thread_access::*;
#[cfg(feature = "serde")]
mod serde;
#[cfg(feature = "gd_test")]
pub use self::serde::tests::*;
// TODO: implement Debug, PartialEq, etc.
/// A `Variant` can represent many of godot's core types.
///
/// The underlying data can be either stored inline or reference-counted,
/// dependning on the size of the type and whether the it is trivially copyable.
pub struct Variant(pub(crate) sys::godot_variant);
macro_rules! variant_constructors {
(
$(
$(#[$attr:meta])*
pub fn $ctor:ident($Type:ty) -> Self;
)*
) => (
$(
$(#[$attr])*
pub fn $ctor(val: $Type) -> Variant {
ToVariant::to_variant(val)
}
)*
)
}
macro_rules! variant_to_type_transmute {
(
$(
$(#[$to_attr:meta])*
pub fn $to_method:ident(&self) -> $ToType:ident : $to_gd_method:ident;
$(#[$try_attr:meta])*
pub fn $try_method:ident(&self) -> Option<$TryType:ident>;
)*
) => (
$(
$(#[$to_attr])*
pub fn $to_method(&self) -> $ToType {
unsafe {
#[allow(clippy::useless_transmute)]
transmute((get_api().$to_gd_method)(&self.0))
}
}
$(#[$try_attr])*
pub fn $try_method(&self) -> Option<$TryType> {
$TryType::from_variant(self).ok()
}
)*
)
}
macro_rules! variant_to_type_from_sys {
(
$(
$(#[$to_attr:meta])*
pub fn $to_method:ident(&self) -> $ToType:ty : $to_gd_method:ident;
$(#[$try_attr:meta])*
pub fn $try_method:ident(&self) -> Option<$TryType:ty>;
)*
) => (
$(
$(#[$to_attr])*
pub fn $to_method(&self) -> $ToType {
unsafe {
<$ToType>::from_sys((get_api().$to_gd_method)(&self.0))
}
}
$(#[$try_attr])*
pub fn $try_method(&self) -> Option<$TryType> {
<$TryType>::from_variant(self).ok()
}
)*
)
}
macro_rules! variant_dispatch_arm {
($v:expr, $variant:ident ( $inner:ty )) => {
VariantDispatch::$variant(<$inner>::from_variant($v).unwrap())
};
($v:expr, $variant:ident) => {
VariantDispatch::$variant
};
}
macro_rules! decl_variant_type {
(
pub enum VariantType, VariantDispatch {
$(
$variant:ident $( ($inner:ty) )? = $c_const:path,
)*
}
) => {
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub enum VariantType {
$(
$variant = $c_const as u32,
)*
}
impl VariantType {
pub const NAMES: &'static [&'static str] = &[
$(stringify!($variant),)*
];
#[inline]
pub fn name(&self) -> &'static str {
match *self {
$(Self::$variant => stringify!($variant),)*
}
}
}
/// Rust enum associating each primitive variant type to its value.
///
/// For `Variant`s containing objects, the original `Variant` is returned unchanged, due to
/// the limitations of statically-determined memory management.
#[derive(Clone, Debug)]
#[repr(u32)]
pub enum VariantDispatch {
$(
$variant $( ($inner) )?,
)*
}
impl<'a> From<&'a Variant> for VariantDispatch {
#[inline]
fn from(v: &'a Variant) -> Self {
match v.get_type() {
$(
VariantType::$variant => {
variant_dispatch_arm!(v, $variant $( ($inner) )?)
},
)*
}
}
}
impl<'a> From<&'a VariantDispatch> for Variant {
#[inline]
fn from(v: &'a VariantDispatch) -> Self {
match v {
$($(VariantDispatch::$variant(v) => {
let v: &$inner = v;
v.to_variant()
})?)*
_ => Variant::new()
}
}
}
}
}
decl_variant_type!(
pub enum VariantType, VariantDispatch {
Nil = sys::godot_variant_type_GODOT_VARIANT_TYPE_NIL,
Bool(bool) = sys::godot_variant_type_GODOT_VARIANT_TYPE_BOOL,
I64(i64) = sys::godot_variant_type_GODOT_VARIANT_TYPE_INT,
F64(f64) = sys::godot_variant_type_GODOT_VARIANT_TYPE_REAL,
GodotString(GodotString) = sys::godot_variant_type_GODOT_VARIANT_TYPE_STRING,
Vector2(Vector2) = sys::godot_variant_type_GODOT_VARIANT_TYPE_VECTOR2,
Rect2(Rect2) = sys::godot_variant_type_GODOT_VARIANT_TYPE_RECT2,
Vector3(Vector3) = sys::godot_variant_type_GODOT_VARIANT_TYPE_VECTOR3,
Transform2D(Transform2D) = sys::godot_variant_type_GODOT_VARIANT_TYPE_TRANSFORM2D,
Plane(Plane) = sys::godot_variant_type_GODOT_VARIANT_TYPE_PLANE,
Quat(Quat) = sys::godot_variant_type_GODOT_VARIANT_TYPE_QUAT,
Aabb(Aabb) = sys::godot_variant_type_GODOT_VARIANT_TYPE_AABB,
Basis(Basis) = sys::godot_variant_type_GODOT_VARIANT_TYPE_BASIS,
Transform(Transform) = sys::godot_variant_type_GODOT_VARIANT_TYPE_TRANSFORM,
Color(Color) = sys::godot_variant_type_GODOT_VARIANT_TYPE_COLOR,
NodePath(NodePath) = sys::godot_variant_type_GODOT_VARIANT_TYPE_NODE_PATH,
Rid(Rid) = sys::godot_variant_type_GODOT_VARIANT_TYPE_RID,
Object(Variant) = sys::godot_variant_type_GODOT_VARIANT_TYPE_OBJECT,
Dictionary(Dictionary) = sys::godot_variant_type_GODOT_VARIANT_TYPE_DICTIONARY,
VariantArray(VariantArray) = sys::godot_variant_type_GODOT_VARIANT_TYPE_ARRAY,
ByteArray(ByteArray) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_BYTE_ARRAY,
Int32Array(Int32Array) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_INT_ARRAY,
Float32Array(Float32Array) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_REAL_ARRAY,
StringArray(StringArray) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_STRING_ARRAY,
Vector2Array(Vector2Array) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_VECTOR2_ARRAY,
Vector3Array(Vector3Array) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_VECTOR3_ARRAY,
ColorArray(ColorArray) = sys::godot_variant_type_GODOT_VARIANT_TYPE_POOL_COLOR_ARRAY,
}
);
impl VariantType {
#[doc(hidden)]
#[inline]
pub fn from_sys(v: sys::godot_variant_type) -> VariantType {
unsafe { transmute(v as u32) }
}
}
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum CallError {
InvalidMethod =
sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_ERROR_INVALID_METHOD as u32,
InvalidArgument =
sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_ERROR_INVALID_ARGUMENT as u32,
TooManyArguments =
sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_ERROR_TOO_MANY_ARGUMENTS as u32,
TooFewArguments =
sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_ERROR_TOO_FEW_ARGUMENTS as u32,
InstanceIsNull =
sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_ERROR_INSTANCE_IS_NULL as u32,
}
impl CallError {
#[inline]
fn from_sys(v: sys::godot_variant_call_error_error) -> Result<(), CallError> {
if v == sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_OK {
Ok(())
} else {
debug_assert!(
(v as u32) <= sys::godot_variant_call_error_error_GODOT_CALL_ERROR_CALL_ERROR_INSTANCE_IS_NULL as u32,
"Godot should have passed a known error",
);
Err(unsafe { transmute(v as u32) })
}
}
}
impl std::fmt::Display for CallError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use CallError::*;
match self {
InvalidMethod => write!(f, "invalid method"),
InvalidArgument => write!(f, "invalid argument"),
TooManyArguments => write!(f, "too many arguments"),
TooFewArguments => write!(f, "too few arguments"),
InstanceIsNull => write!(f, "instance is null"),
}
}
}
impl std::error::Error for CallError {}
/// Godot variant operator kind.
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum VariantOperator {
// Comparison
Equal = sys::godot_variant_operator_GODOT_VARIANT_OP_EQUAL as u32,
NotEqual = sys::godot_variant_operator_GODOT_VARIANT_OP_NOT_EQUAL as u32,
Less = sys::godot_variant_operator_GODOT_VARIANT_OP_LESS as u32,
LessEqual = sys::godot_variant_operator_GODOT_VARIANT_OP_LESS_EQUAL as u32,
Greater = sys::godot_variant_operator_GODOT_VARIANT_OP_GREATER as u32,
GreaterEqual = sys::godot_variant_operator_GODOT_VARIANT_OP_GREATER_EQUAL as u32,
// Mathematic
Add = sys::godot_variant_operator_GODOT_VARIANT_OP_ADD as u32,
Subtract = sys::godot_variant_operator_GODOT_VARIANT_OP_SUBTRACT as u32,
Multiply = sys::godot_variant_operator_GODOT_VARIANT_OP_MULTIPLY as u32,
Divide = sys::godot_variant_operator_GODOT_VARIANT_OP_DIVIDE as u32,
Negate = sys::godot_variant_operator_GODOT_VARIANT_OP_NEGATE as u32,
Positive = sys::godot_variant_operator_GODOT_VARIANT_OP_POSITIVE as u32,
Module = sys::godot_variant_operator_GODOT_VARIANT_OP_MODULE as u32,
StringConcat = sys::godot_variant_operator_GODOT_VARIANT_OP_STRING_CONCAT as u32,
// Bitwise
ShiftLeft = sys::godot_variant_operator_GODOT_VARIANT_OP_SHIFT_LEFT as u32,
ShiftRight = sys::godot_variant_operator_GODOT_VARIANT_OP_SHIFT_RIGHT as u32,
BitAnd = sys::godot_variant_operator_GODOT_VARIANT_OP_BIT_AND as u32,
BitOr = sys::godot_variant_operator_GODOT_VARIANT_OP_BIT_OR as u32,
BitXor = sys::godot_variant_operator_GODOT_VARIANT_OP_BIT_XOR as u32,
BitNegate = sys::godot_variant_operator_GODOT_VARIANT_OP_BIT_NEGATE as u32,
// Logic
And = sys::godot_variant_operator_GODOT_VARIANT_OP_AND as u32,
Or = sys::godot_variant_operator_GODOT_VARIANT_OP_OR as u32,
Xor = sys::godot_variant_operator_GODOT_VARIANT_OP_XOR as u32,
Not = sys::godot_variant_operator_GODOT_VARIANT_OP_NOT as u32,
// Containment
In = sys::godot_variant_operator_GODOT_VARIANT_OP_IN as u32,
}
impl VariantOperator {
const MAX: u32 = sys::godot_variant_operator_GODOT_VARIANT_OP_MAX as u32;
#[doc(hidden)]
#[inline]
pub fn to_sys(self) -> sys::godot_variant_operator {
self as u32 as sys::godot_variant_operator
}
#[doc(hidden)]
#[inline]
pub fn try_from_sys(op: sys::godot_variant_operator) -> Option<Self> {
let op = op as u32;
if op >= Self::MAX {
return None;
}
// SAFETY: Max value is checked, and Self is repr(u32)
unsafe { std::mem::transmute(op) }
}
}
/// Error indicating that an operator result is invalid.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Default, Debug)]
pub struct InvalidOp;
//fn to_godot_varianty_type(v: VariantType) -> sys::godot_variant_type {
// unsafe { transmute(v) }
//}
// These aliases are just here so the type name matches the VariantType's variant names
// to make writing macros easier.
type F64 = f64;
type I64 = i64;
type Bool = bool;
impl Variant {
variant_constructors!(
/// Creates a `Variant` wrapping a `Vector2`.
#[inline]
pub fn from_vector2(&Vector2) -> Self;
/// Creates a `Variant` wrapping a `Vector3`.
#[inline]
pub fn from_vector3(&Vector3) -> Self;
/// Creates a `Variant` wrapping a `Quat`.
#[inline]
pub fn from_quat(&Quat) -> Self;
/// Creates a `Variant` wrapping a `Plane`.
#[inline]
pub fn from_plane(&Plane) -> Self;
/// Creates a `Variant` wrapping a `Rect2`.
#[inline]
pub fn from_rect2(&Rect2) -> Self;
/// Creates a `Variant` wrapping a `Transform`.
#[inline]
pub fn from_transform(&Transform) -> Self;
/// Creates a `Variant` wrapping a `Transform2D`.
#[inline]
pub fn from_transform2d(&Transform2D) -> Self;
/// Creates a `Variant` wrapping a `Basis`.
#[inline]
pub fn from_basis(&Basis) -> Self;
/// Creates a `Variant` wrapping a `Color`.
#[inline]
pub fn from_color(&Color) -> Self;
/// Creates a `Variant` wrapping an `Aabb`.
#[inline]
pub fn from_aabb(&Aabb) -> Self;
/// Creates a `Variant` wrapping an `Rid`.
#[inline]
pub fn from_rid(&Rid) -> Self;
/// Creates a `Variant` wrapping a `NodePath`.
#[inline]
pub fn from_node_path(&NodePath) -> Self;
/// Creates a `Variant` wrapping a `GodotString`.
#[inline]
pub fn from_godot_string(&GodotString) -> Self;
/// Creates an `Variant` wrapping an array of variants.
#[inline]
pub fn from_array(&VariantArray<Shared>) -> Self;
/// Creates a `Variant` wrapping a byte array.
#[inline]
pub fn from_byte_array(&ByteArray) -> Self;
/// Creates a `Variant` wrapping an array of 32bit signed integers.
#[inline]
pub fn from_int32_array(&Int32Array) -> Self;
/// Creates a `Variant` wrapping an array of 32bit floats.
#[inline]
pub fn from_float32_array(&Float32Array) -> Self;
/// Creates a `Variant` wrapping an array of godot strings.
#[inline]
pub fn from_string_array(&StringArray) -> Self;
/// Creates a `Variant` wrapping an array of 2d vectors.
#[inline]
pub fn from_vector2_array(&Vector2Array) -> Self;
/// Creates a `Variant` wrapping an array of 3d vectors.
#[inline]
pub fn from_vector3_array(&Vector3Array) -> Self;
/// Creates a `Variant` wrapping an array of colors.
#[inline]
pub fn from_color_array(&ColorArray) -> Self;
/// Creates a `Variant` wrapping a dictionary.
#[inline]
pub fn from_dictionary(&Dictionary<Shared>) -> Self;
);
/// Creates an empty `Variant`.
#[inline]
pub fn new() -> Self {
unsafe {
let api = get_api();
let mut dest = sys::godot_variant::default();
(api.godot_variant_new_nil)(&mut dest);
Variant(dest)
}
}
/// Creates a `Variant` wrapping a string.
#[inline]
#[allow(clippy::should_implement_trait)]
pub fn from_str<S>(s: S) -> Variant
where
S: AsRef<str>,
{
unsafe {
let api = get_api();
let mut dest = sys::godot_variant::default();
let val = s.as_ref();
let mut godot_s =
(api.godot_string_chars_to_utf8_with_len)(val.as_ptr() as *const _, val.len() as _);
(api.godot_variant_new_string)(&mut dest, &godot_s);
(api.godot_string_destroy)(&mut godot_s);
Variant(dest)
}
}
/// Creates a `Variant` wrapping a Godot object.
#[inline]
pub fn from_object<R>(val: R) -> Variant
where
R: AsVariant,
{
unsafe { R::to_arg_variant(&val) }
}
/// Creats a `Variant` from a raw object pointer.
///
/// # Safety
///
/// The object pointer must be a valid pointer to a godot object.
#[doc(hidden)]
#[inline]
pub unsafe fn from_object_ptr(val: *mut sys::godot_object) -> Variant {
let api = get_api();
let mut dest = sys::godot_variant::default();
(api.godot_variant_new_object)(&mut dest, val);
Variant(dest)
}
/// Creates a `Variant` wrapping a signed integer value.
#[inline]
pub fn from_i64(v: i64) -> Variant {
unsafe {
let api = get_api();
let mut dest = sys::godot_variant::default();
(api.godot_variant_new_int)(&mut dest, v);
Variant(dest)
}
}
/// Creates a `Variant` wrapping an unsigned integer value.
#[inline]
pub fn from_u64(v: u64) -> Variant {
unsafe {
let api = get_api();
let mut dest = sys::godot_variant::default();
(api.godot_variant_new_uint)(&mut dest, v);
Variant(dest)
}
}
/// Creates a `Variant` wrapping a double-precision float value.
#[inline]
pub fn from_f64(v: f64) -> Variant {
unsafe {
let api = get_api();
let mut ret = sys::godot_variant::default();
(api.godot_variant_new_real)(&mut ret, v);
Variant(ret)
}
}
/// Creates a `Variant` wrapping an boolean.
#[inline]
pub fn from_bool(v: bool) -> Variant {
unsafe {
let api = get_api();
let mut dest = sys::godot_variant::default();
(api.godot_variant_new_bool)(&mut dest, v);
Variant(dest)
}
}
#[inline]
fn try_as_sys_of_type(
&self,
expected: VariantType,
) -> Result<&sys::godot_variant, FromVariantError> {
let variant_type = self.get_type();
if variant_type != expected {
return Err(FromVariantError::InvalidVariantType {
expected,
variant_type,
});
}
Ok(&self.0)
}
variant_to_type_transmute!(
/// Do a best effort to create a `Vector2` out of the variant, possibly returning a default value.
#[inline]
pub fn to_vector2(&self) -> Vector2 : godot_variant_as_vector2;
/// Returns `Some(Vector2)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_vector2(&self) -> Option<Vector2>;
/// Do a best effort to create a `Vector3` out of the variant, possibly returning a default value.
#[inline]
pub fn to_vector3(&self) -> Vector3 : godot_variant_as_vector3;
/// Returns `Some(Vector3)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_vector3(&self) -> Option<Vector3>;
/// Do a best effort to create a `Quat` out of the variant, possibly returning a default value.
#[inline]
pub fn to_quat(&self) -> Quat : godot_variant_as_quat;
/// Returns `Some(Quat)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_quat(&self) -> Option<Quat>;
/// Do a best effort to create a `Rect2` out of the variant, possibly returning a default value.
#[inline]
pub fn to_rect2(&self) -> Rect2 : godot_variant_as_rect2;
/// Returns `Some(Rect2)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_rect2(&self) -> Option<Rect2>;
/// Do a best effort to create a `Transform2D` out of the variant, possibly returning a default value.
#[inline]
pub fn to_transform2d(&self) -> Transform2D : godot_variant_as_transform2d;
/// Returns `Some(Transform2D)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_transform2d(&self) -> Option<Transform2D>;
/// Do a best effort to create a `f64` out of the variant, possibly returning a default value.
#[inline]
pub fn to_f64(&self) -> F64 : godot_variant_as_real;
/// Returns `Some(f64)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_f64(&self) -> Option<F64>;
/// Do a best effort to create an `i64` out of the variant, possibly returning a default value.
#[inline]
pub fn to_i64(&self) -> I64 : godot_variant_as_int;
/// Returns `Some(i64)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_i64(&self) -> Option<I64>;
/// Do a best effort to create a `bool` out of the variant, possibly returning a default value.
#[inline]
pub fn to_bool(&self) -> Bool : godot_variant_as_bool;
/// Returns `Some(bool)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_bool(&self) -> Option<Bool>;
);
/// Do a best effort to create a `u64` out of the variant, possibly returning a default value.
#[inline]
pub fn to_u64(&self) -> u64 {
unsafe {
let api = get_api();
(api.godot_variant_as_uint)(&self.0)
}
}
/// Returns `Some(u64)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_u64(&self) -> Option<u64> {
unsafe {
let api = get_api();
if (api.godot_variant_get_type)(&self.0)
== sys::godot_variant_type_GODOT_VARIANT_TYPE_INT
{
Some((api.godot_variant_as_uint)(&self.0))
} else {
None
}
}
}
variant_to_type_from_sys!(
/// Do a best effort to create a `Plane` out of the variant, possibly returning a default value.
#[inline]
pub fn to_plane(&self) -> Plane : godot_variant_as_plane;
/// Returns `Some(Plane)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_plane(&self) -> Option<Plane>;
/// Do a best effort to create a `Transform` out of the variant, possibly returning a default value.
#[inline]
pub fn to_transform(&self) -> Transform : godot_variant_as_transform;
/// Returns `Some(Transform)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_transform(&self) -> Option<Transform>;
/// Do a best effort to create a `Color` out of the variant, possibly returning a default value.
#[inline]
pub fn to_color(&self) -> Color : godot_variant_as_color;
/// Returns `Some(Color)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_color(&self) -> Option<Color>;
/// Do a best effort to create a `Basis` out of the variant, possibly returning a default value.
#[inline]
pub fn to_basis(&self) -> Basis : godot_variant_as_basis;
/// Returns `Some(Basis)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_basis(&self) -> Option<Basis>;
/// Do a best effort to create an `Aabb` out of the variant, possibly returning a default value.
#[inline]
pub fn to_aabb(&self) -> Aabb : godot_variant_as_aabb;
/// Returns `Some(Aabb)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_aabb(&self) -> Option<Aabb>;
/// Do a best effort to create a `NodePath` out of the variant, possibly returning a default value.
#[inline]
pub fn to_node_path(&self) -> NodePath : godot_variant_as_node_path;
/// Returns `Some(NodePath)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_node_path(&self) -> Option<NodePath>;
/// Do a best effort to create a `GodotString` out of the variant, possibly returning a default value.
#[inline]
pub fn to_godot_string(&self) -> GodotString : godot_variant_as_string;
/// Returns `Some(GodotString)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_godot_string(&self) -> Option<GodotString>;
/// Do a best effort to create a `Rid` out of the variant, possibly returning a default value.
#[inline]
pub fn to_rid(&self) -> Rid : godot_variant_as_rid;
/// Returns `Some(Rid)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_rid(&self) -> Option<Rid>;
/// Do a best effort to create a `VariantArray` out of the variant, possibly returning a default value.
#[inline]
pub fn to_array(&self) -> VariantArray<Shared> : godot_variant_as_array;
/// Returns `Some(VariantArray)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_array(&self) -> Option<VariantArray<Shared>>;
/// Do a best effort to create a `ByteArray` out of the variant, possibly returning a default value.
#[inline]
pub fn to_byte_array(&self) -> ByteArray : godot_variant_as_pool_byte_array;
/// Returns `Some(ByteArray)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_byte_array(&self) -> Option<ByteArray>;
/// Do a best effort to create an `Int32Array` out of the variant, possibly returning a default value.
#[inline]
pub fn to_int32_array(&self) -> Int32Array : godot_variant_as_pool_int_array;
/// Returns `Some(Int32Array)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_int32_array(&self) -> Option<Int32Array>;
/// Do a best effort to create a `Float32Array` out of the variant, possibly returning a default value.
#[inline]
pub fn to_float32_array(&self) -> Float32Array : godot_variant_as_pool_real_array;
/// Returns `Some(Float32Array)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_float32_array(&self) -> Option<Float32Array>;
/// Do a best effort to create a `StringArray` out of the variant, possibly returning a default value.
#[inline]
pub fn to_string_array(&self) -> StringArray : godot_variant_as_pool_string_array;
/// Returns `Some(StringArray)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_string_array(&self) -> Option<StringArray>;
/// Do a best effort to create a `Vector2Array` out of the variant, possibly returning a default value.
#[inline]
pub fn to_vector2_array(&self) -> Vector2Array : godot_variant_as_pool_vector2_array;
/// Returns `Some(Vector2Array)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_vector2_array(&self) -> Option<Vector2Array>;
/// Do a best effort to create a `Vector3Array` out of the variant, possibly returning a default value.
#[inline]
pub fn to_vector3_array(&self) -> Vector3Array : godot_variant_as_pool_vector3_array;
/// Returns `Some(Vector3Array)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_vector3_array(&self) -> Option<Vector3Array>;
/// Do a best effort to create a `ColorArray` out of the variant, possibly returning a default value.
#[inline]
pub fn to_color_array(&self) -> ColorArray : godot_variant_as_pool_color_array;
/// Returns `Some(ColorArray)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_color_array(&self) -> Option<ColorArray>;
/// Do a best effort to create a `Dictionary` out of the variant, possibly returning a default value.
#[inline]
pub fn to_dictionary(&self) -> Dictionary<Shared> : godot_variant_as_dictionary;
/// Returns `Some(Dictionary)` if this variant is one, `None` otherwise.
#[inline]
pub fn try_to_dictionary(&self) -> Option<Dictionary<Shared>>;
);
#[inline]
pub fn try_to_object<T>(&self) -> Option<Ref<T, Shared>>
where
T: GodotObject,
{
self.try_to_object_with_error::<T>().ok()
}
#[inline]
pub fn try_to_object_with_error<T>(&self) -> Result<Ref<T, Shared>, FromVariantError>
where
T: GodotObject,
{
unsafe {
let api = get_api();
let obj = self.try_as_sys_of_type(VariantType::Object)?;
let obj = ptr::NonNull::new((api.godot_variant_as_object)(obj))
.ok_or(FromVariantError::InvalidNil)?;
let obj =
object::RawObject::<ManuallyManagedClassPlaceholder>::from_sys_ref_unchecked(obj);
let obj = obj
.cast::<T>()
.ok_or_else(|| FromVariantError::CannotCast {
class: obj.class_name(),
to: T::class_name(),
})?;
Ok(Ref::from_sys(obj.sys()))
}
}
#[inline]
pub fn try_to_string(&self) -> Option<String> {
self.try_to_godot_string().map(|s| s.to_string())
}
/// Returns this variant's type.
#[inline]
pub fn get_type(&self) -> VariantType {
unsafe { VariantType::from_sys((get_api().godot_variant_get_type)(&self.0)) }
}
/// Converts this variant to a primitive value depending on its type.
///
/// # Examples
///
/// ```ignore
/// let variant = 42.to_variant();
/// let number_as_float = match variant.dispatch() {
/// VariantDispatch::I64(i) => i as f64,
/// VariantDispatch::F64(f) => f,
/// _ => panic!("not a number"),
/// };
/// approx::assert_relative_eq!(42.0, number_as_float);
/// ```
#[inline]
pub fn dispatch(&self) -> VariantDispatch {
self.into()
}
/// Returns true if this is an empty variant.
#[inline]
pub fn is_nil(&self) -> bool {
self.get_type() == VariantType::Nil
}
#[inline]
pub fn has_method(&self, method: impl Into<GodotString>) -> bool {
let method = method.into();
unsafe { (get_api().godot_variant_has_method)(&self.0, &method.0) }
}
#[inline]
pub fn call(
&mut self,
method: impl Into<GodotString>,
args: &[Variant],
) -> Result<Variant, CallError> {
let method = method.into();
unsafe {
let api = get_api();
let mut err = sys::godot_variant_call_error::default();
let mut arg_refs = args.iter().map(Variant::sys).collect::<Vec<_>>();
let variant = (api.godot_variant_call)(
&mut self.0,
&method.0,
arg_refs.as_mut_ptr(),
args.len() as i32,
&mut err,
);
CallError::from_sys(err.error).map(|_| Variant::from_sys(variant))
}
}
/// Evaluates a variant operator on `self` and `rhs` and returns the result on success.
///
/// # Errors
///
/// Returns `Err(InvalidOp)` if the result is not valid.
#[inline]
pub fn evaluate(&self, op: VariantOperator, rhs: &Self) -> Result<Variant, InvalidOp> {
unsafe {
let api = get_api();
let mut ret = Variant::new();
let mut valid = false;
(api.godot_variant_evaluate)(
op.to_sys(),
self.sys(),
rhs.sys(),
ret.sys_mut(),
&mut valid,
);
if valid {
Ok(ret)
} else {
Err(InvalidOp)
}
}
}
/// Get a reference to a `godot-rust` Variant from a raw sys::pointer.
///
/// # Safety
///
/// The pointer must be a valid pointer to a `sys::godot_variant`.
#[inline]
pub(crate) unsafe fn cast_ref<'l>(ptr: *const sys::godot_variant) -> &'l Variant {
&*(ptr as *const variant::Variant)
}
#[inline]
pub(crate) fn cast_mut_ref<'l>(ptr: *mut sys::godot_variant) -> &'l mut Variant {
unsafe { &mut *(ptr as *mut variant::Variant) }
}
/// Returns the internal ffi representation of the variant and consumes
/// the rust object without running the destructor.
///
/// This should be only used when certain that the receiving side is
/// responsible for running the destructor for the object, otherwise
/// it is leaked.
#[inline]
pub fn forget(self) -> sys::godot_variant {
let v = self.0;
forget(self);
v
}
// Returns a copy of the internal ffi representation of the variant.
//
// The variant remains owned by the rust wrapper and the receiver of
// the ffi representation should not run its destructor.
#[doc(hidden)]
#[inline]
pub fn to_sys(&self) -> sys::godot_variant {
self.0
}
#[doc(hidden)]
#[inline]
pub fn sys(&self) -> *const sys::godot_variant {
&self.0
}
#[doc(hidden)]
#[inline]
pub fn sys_mut(&mut self) -> *mut sys::godot_variant {
&mut self.0
}
#[doc(hidden)]
#[inline]
pub fn from_sys(sys: sys::godot_variant) -> Self {
Variant(sys)
}
}
impl_basic_traits_as_sys!(
for Variant as godot_variant {
Drop => godot_variant_destroy;
Clone => godot_variant_new_copy;
PartialEq => godot_variant_operator_equal;
}
);
impl Eq for Variant {}
impl ToString for Variant {
#[inline]
fn to_string(&self) -> String {
self.to_godot_string().to_string()
}
}
impl Default for Variant {
#[inline]
fn default() -> Self {
Variant::new()
}
}
impl fmt::Debug for Variant {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}({})", self.get_type(), self.to_string())
}
}
godot_test!(
test_variant_nil {
let nil = Variant::new();
assert_eq!(nil.get_type(), VariantType::Nil);
assert!(nil.is_nil());
assert!(nil.try_to_array().is_none());
assert!(nil.try_to_rid().is_none());
assert!(nil.try_to_i64().is_none());
assert!(nil.try_to_bool().is_none());
assert!(nil.try_to_aabb().is_none());
assert!(nil.try_to_vector2().is_none());
assert!(nil.try_to_basis().is_none());
assert!(!nil.has_method("foo"));
let clone = nil.clone();
assert!(clone == nil);
}
test_variant_i64 {
let v_42 = Variant::from_i64(42);
assert_eq!(v_42.get_type(), VariantType::I64);
assert!(!v_42.is_nil());
assert_eq!(v_42.try_to_i64(), Some(42));
assert!(v_42.try_to_f64().is_none());
assert!(v_42.try_to_array().is_none());
let v_m1 = Variant::from_i64(-1);
assert_eq!(v_m1.get_type(), VariantType::I64);
assert!(!v_m1.is_nil());
assert_eq!(v_m1.try_to_i64(), Some(-1));
assert!(v_m1.try_to_f64().is_none());
assert!(v_m1.try_to_array().is_none());
}
test_variant_bool {
let v_true = Variant::from_bool(true);
assert_eq!(v_true.get_type(), VariantType::Bool);
assert!(!v_true.is_nil());
assert_eq!(v_true.try_to_bool(), Some(true));
assert!(v_true.try_to_f64().is_none());
assert!(v_true.try_to_array().is_none());
let v_false = Variant::from_bool(false);
assert_eq!(v_false.get_type(), VariantType::Bool);
assert!(!v_false.is_nil());
assert_eq!(v_false.try_to_bool(), Some(false));
assert!(v_false.try_to_f64().is_none());
assert!(v_false.try_to_array().is_none());
}
);
/// Types that can be converted to a `Variant`.
///
/// ## Wrappers and collections
///
/// Implementations are provided for a few common Rust wrappers and collections:
///
/// - `Option<T>` is unwrapped to inner value, or `Nil` if `None`
/// - `Result<T, E>` is represented as an externally tagged `Dictionary` (see below).
/// - `PhantomData<T>` is represented as `Nil`.
/// - `&[T]` and `Vec<T>` are represented as `VariantArray`s. `FromVariant` is only implemented
/// for `Vec<T>`.
///
/// ## Deriving `ToVariant`