Skip to content

Commit 1a2ea68

Browse files
committed
Add GString == &str equality operator
Easier than converting to String/GString, and requires no allocation.
1 parent a8f4fa4 commit 1a2ea68

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

godot-core/src/builtin/string/gstring.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,21 @@ impl fmt::Debug for GString {
323323
}
324324
}
325325

326+
// ----------------------------------------------------------------------------------------------------------------------------------------------
327+
// Comparison with Rust strings
328+
329+
// API design:
330+
// * StringName and NodePath don't implement PartialEq<&str> yet, because they require allocation (convert to GString).
331+
// == should ideally not allocate.
332+
// * Reverse `impl PartialEq<GString> for &str` is not implemented now. Comparisons usually take the form of variable == "literal".
333+
// Can be added later if there are good use-cases.
334+
335+
impl PartialEq<&str> for GString {
336+
fn eq(&self, other: &&str) -> bool {
337+
self.chars().iter().copied().eq(other.chars())
338+
}
339+
}
340+
326341
// ----------------------------------------------------------------------------------------------------------------------------------------------
327342
// Conversion from/into Rust string-types
328343

itest/rust/src/builtin_tests/string/gstring_test.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ fn string_equality() {
4040
assert_ne!(string, different);
4141
}
4242

43+
#[itest]
44+
fn string_eq_str() {
45+
let gstring = GString::from("hello");
46+
assert_eq!(gstring, "hello");
47+
assert_ne!(gstring, "hallo");
48+
}
49+
4350
#[itest]
4451
fn string_ordering() {
4552
let low = GString::from("Alpha");

0 commit comments

Comments
 (0)