Skip to content

Implement From<&[char]> for GString #862

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions godot-core/src/builtin/string/gstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,22 @@ impl From<&str> for GString {
}
}

impl From<&[char]> for GString {
fn from(chars: &[char]) -> Self {
// SAFETY: A `char` value is by definition a valid Unicode code point.
unsafe {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this isn't completely obvious, you should maybe add a // SAFETY line saying something about UTF-32.

Self::new_with_string_uninit(|string_ptr| {
let ctor = interface_fn!(string_new_with_utf32_chars_and_len);
ctor(
string_ptr,
chars.as_ptr() as *const sys::char32_t,
chars.len() as i64,
);
})
}
}
}

impl From<String> for GString {
fn from(value: String) -> Self {
value.as_str().into()
Expand Down
5 changes: 4 additions & 1 deletion itest/rust/src/builtin_tests/string/gstring_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,16 @@ fn string_clone() {
fn string_chars() {
// Empty tests regression from #228: Null pointer passed to slice::from_raw_parts().
let string = GString::new();
assert_eq!(string.chars(), &[]);
let empty_char_slice: &[char] = &[];
assert_eq!(string.chars(), empty_char_slice);
assert_eq!(string, GString::from(empty_char_slice));

let string = String::from("some_string");
let string_chars: Vec<char> = string.chars().collect();
let gstring = GString::from(string);

assert_eq!(string_chars, gstring.chars().to_vec());
assert_eq!(gstring, GString::from(string_chars.as_slice()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case I'd say it's fine because Vec<char> is just explicitly declared above, and Vec::as_slice() is sufficiently clear 👍

}

#[itest]
Expand Down
Loading