godot_core/builtin/string/gstring.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::convert::Infallible;
9use std::fmt;
10use std::fmt::Write;
11
12use godot_ffi as sys;
13use sys::types::OpaqueString;
14use sys::{ffi_methods, interface_fn, ExtVariantType, GodotFfi};
15
16use crate::builtin::string::{pad_if_needed, Encoding};
17use crate::builtin::{inner, NodePath, StringName, Variant};
18use crate::meta::error::StringError;
19use crate::meta::AsArg;
20use crate::{impl_shared_string_api, meta};
21
22/// Godot's reference counted string type.
23///
24/// This is the Rust binding of GDScript's `String` type. It represents the native string class used within the Godot engine,
25/// and as such has different memory layout and characteristics than `std::string::String`.
26///
27/// `GString` uses copy-on-write semantics and is cheap to clone. Modifying a string may trigger a copy, if that instance shares
28/// its backing storage with other strings.
29///
30/// Note that `GString` is not immutable, but it offers a very limited set of write APIs. Most operations return new strings.
31/// In order to modify Godot strings, it's often easiest to convert them to Rust strings, perform the modifications and convert back.
32///
33/// # `GString` vs. `String`
34///
35/// When interfacing with the Godot engine API, you often have the choice between `String` and `GString`. In user-declared methods
36/// exposed to Godot through the `#[func]` attribute, both types can be used as parameters and return types, and conversions
37/// are done transparently. For auto-generated binding APIs in `godot::classes`, both parameters and return types are `GString`.
38/// Parameters are declared as `impl AsArg<GString>`, allowing you to be more flexible with arguments such as `"some_string"`.
39///
40/// As a general guideline, use `GString` if:
41/// * your strings are very large, so you can avoid copying them
42/// * you need specific operations only available in Godot (e.g. `sha256_text()`, `c_escape()`, ...)
43/// * you primarily pass them between different Godot APIs, without string processing in user code
44///
45/// Use Rust's `String` if:
46/// * you need to modify the string
47/// * you would like to decouple part of your code from Godot (e.g. independent game logic, standalone tests)
48/// * you want a standard type for interoperability with third-party code (e.g. `regex` crate)
49/// * you have a large number of method calls per string instance (which are more expensive due to indirectly calling into Godot)
50/// * you need UTF-8 encoding (`GString` uses UTF-32)
51///
52/// # Null bytes
53///
54/// Note that Godot ignores any bytes after a null-byte. This means that for instance `"hello, world!"` and `"hello, world!\0 ignored by Godot"`
55/// will be treated as the same string if converted to a `GString`.
56///
57/// # All string types
58///
59/// | Intended use case | String type |
60/// |-------------------|--------------------------------------------|
61/// | General purpose | **`GString`** |
62/// | Interned names | [`StringName`][crate::builtin::StringName] |
63/// | Scene-node paths | [`NodePath`][crate::builtin::NodePath] |
64///
65/// # Godot docs
66///
67/// [`String` (stable)](https://docs.godotengine.org/en/stable/classes/class_string.html)
68#[doc(alias = "String")]
69// #[repr] is needed on GString itself rather than the opaque field, because PackedStringArray::as_slice() relies on a packed representation.
70#[repr(transparent)]
71pub struct GString {
72 _opaque: OpaqueString,
73}
74
75// SAFETY: The Godot implementation of String uses an atomic copy on write pointer, making this thread-safe as we never write to it unless we own it.
76unsafe impl Send for GString {}
77
78impl GString {
79 /// Construct a new empty `GString`.
80 pub fn new() -> Self {
81 Self::default()
82 }
83
84 /// Convert string from bytes with given encoding, returning `Err` on validation errors.
85 ///
86 /// Intermediate `NUL` characters are not accepted in Godot and always return `Err`.
87 ///
88 /// Some notes on the encodings:
89 /// - **Latin-1:** Since every byte is a valid Latin-1 character, no validation besides the `NUL` byte is performed.
90 /// It is your responsibility to ensure that the input is meaningful under Latin-1.
91 /// - **ASCII**: Subset of Latin-1, which is additionally validated to be valid, non-`NUL` ASCII characters.
92 /// - **UTF-8**: The input is validated to be UTF-8.
93 ///
94 /// Specifying incorrect encoding is safe, but may result in unintended string values.
95 pub fn try_from_bytes(bytes: &[u8], encoding: Encoding) -> Result<Self, StringError> {
96 Self::try_from_bytes_with_nul_check(bytes, encoding, true)
97 }
98
99 /// Convert string from C-string with given encoding, returning `Err` on validation errors.
100 ///
101 /// Convenience function for [`try_from_bytes()`](Self::try_from_bytes); see its docs for more information.
102 pub fn try_from_cstr(cstr: &std::ffi::CStr, encoding: Encoding) -> Result<Self, StringError> {
103 Self::try_from_bytes_with_nul_check(cstr.to_bytes(), encoding, false)
104 }
105
106 pub(super) fn try_from_bytes_with_nul_check(
107 bytes: &[u8],
108 encoding: Encoding,
109 check_nul: bool,
110 ) -> Result<Self, StringError> {
111 match encoding {
112 Encoding::Ascii => {
113 // If the bytes are ASCII, we can fall back to Latin-1, which is always valid (except for NUL).
114 // is_ascii() does *not* check for the NUL byte, so the check in the Latin-1 branch is still necessary.
115 if bytes.is_ascii() {
116 Self::try_from_bytes_with_nul_check(bytes, Encoding::Latin1, check_nul)
117 .map_err(|_e| StringError::new("intermediate NUL byte in ASCII string"))
118 } else {
119 Err(StringError::new("invalid ASCII"))
120 }
121 }
122 Encoding::Latin1 => {
123 // Intermediate NUL bytes are not accepted in Godot. Both ASCII + Latin-1 encodings need to explicitly check for this.
124 if check_nul && bytes.contains(&0) {
125 // Error overwritten when called from ASCII branch.
126 return Err(StringError::new("intermediate NUL byte in Latin-1 string"));
127 }
128
129 let s = unsafe {
130 Self::new_with_string_uninit(|string_ptr| {
131 let ctor = interface_fn!(string_new_with_latin1_chars_and_len);
132 ctor(
133 string_ptr,
134 bytes.as_ptr() as *const std::ffi::c_char,
135 bytes.len() as i64,
136 );
137 })
138 };
139 Ok(s)
140 }
141 Encoding::Utf8 => {
142 // from_utf8() also checks for intermediate NUL bytes.
143 let utf8 = std::str::from_utf8(bytes);
144
145 utf8.map(GString::from)
146 .map_err(|e| StringError::with_source("invalid UTF-8", e))
147 }
148 }
149 }
150
151 /// Number of characters in the string.
152 ///
153 /// _Godot equivalent: `length`_
154 #[doc(alias = "length")]
155 pub fn len(&self) -> usize {
156 self.as_inner().length().try_into().unwrap()
157 }
158
159 /// Returns a 32-bit integer hash value representing the string.
160 pub fn hash(&self) -> u32 {
161 self.as_inner()
162 .hash()
163 .try_into()
164 .expect("Godot hashes are uint32_t")
165 }
166
167 /// Gets the UTF-32 character slice from a `GString`.
168 pub fn chars(&self) -> &[char] {
169 // SAFETY: Godot 4.1 ensures valid UTF-32, making interpreting as char slice safe.
170 // See https://github.com/godotengine/godot/pull/74760.
171 unsafe {
172 let s = self.string_sys();
173 let len = interface_fn!(string_to_utf32_chars)(s, std::ptr::null_mut(), 0);
174 let ptr = interface_fn!(string_operator_index_const)(s, 0);
175
176 // Even when len == 0, from_raw_parts requires ptr != null.
177 if ptr.is_null() {
178 return &[];
179 }
180
181 std::slice::from_raw_parts(ptr as *const char, len as usize)
182 }
183 }
184
185 ffi_methods! {
186 type sys::GDExtensionStringPtr = *mut Self;
187
188 fn new_from_string_sys = new_from_sys;
189 fn new_with_string_uninit = new_with_uninit;
190 fn string_sys = sys;
191 fn string_sys_mut = sys_mut;
192 }
193
194 /// Consumes self and turns it into a sys-ptr, should be used together with [`from_owned_string_sys`](Self::from_owned_string_sys).
195 ///
196 /// This will leak memory unless `from_owned_string_sys` is called on the returned pointer.
197 pub(crate) fn into_owned_string_sys(self) -> sys::GDExtensionStringPtr {
198 sys::static_assert_eq_size_align!(StringName, sys::types::OpaqueString);
199
200 let leaked = Box::into_raw(Box::new(self));
201 leaked.cast()
202 }
203
204 /// Creates a `GString` from a sys-ptr without incrementing the refcount.
205 ///
206 /// # Safety
207 ///
208 /// * Must only be used on a pointer returned from a call to [`into_owned_string_sys`](Self::into_owned_string_sys).
209 /// * Must not be called more than once on the same pointer.
210 #[deny(unsafe_op_in_unsafe_fn)]
211 pub(crate) unsafe fn from_owned_string_sys(ptr: sys::GDExtensionStringPtr) -> Self {
212 sys::static_assert_eq_size_align!(StringName, sys::types::OpaqueString);
213
214 let ptr = ptr.cast::<Self>();
215
216 // SAFETY: `ptr` was returned from a call to `into_owned_string_sys`, which means it was created by a call to
217 // `Box::into_raw`, thus we can use `Box::from_raw` here. Additionally, this is only called once on this pointer.
218 let boxed = unsafe { Box::from_raw(ptr) };
219 *boxed
220 }
221
222 /// Convert a `GString` sys pointer to a mutable reference with unbounded lifetime.
223 ///
224 /// # Safety
225 ///
226 /// - `ptr` must point to a live `GString` for the duration of `'a`.
227 /// - Must be exclusive - no other reference to given `GString` instance can exist for the duration of `'a`.
228 pub(crate) unsafe fn borrow_string_sys_mut<'a>(ptr: sys::GDExtensionStringPtr) -> &'a mut Self {
229 sys::static_assert_eq_size_align!(StringName, sys::types::OpaqueString);
230 &mut *(ptr.cast::<GString>())
231 }
232
233 /// Moves this string into a string sys pointer. This is the same as using [`GodotFfi::move_return_ptr`].
234 ///
235 /// # Safety
236 ///
237 /// `dst` must be a valid string pointer.
238 pub(crate) unsafe fn move_into_string_ptr(self, dst: sys::GDExtensionStringPtr) {
239 let dst: sys::GDExtensionTypePtr = dst.cast();
240
241 self.move_return_ptr(dst, sys::PtrcallType::Standard);
242 }
243
244 meta::declare_arg_method! {
245 /// Use as argument for an [`impl AsArg<StringName|NodePath>`][crate::meta::AsArg] parameter.
246 ///
247 /// This is a convenient way to convert arguments of similar string types.
248 ///
249 /// # Example
250 /// [`Node::has_node()`][crate::classes::Node::has_node] takes `NodePath`, let's pass a `GString`:
251 /// ```no_run
252 /// # use godot::prelude::*;
253 /// let name = GString::from("subnode");
254 ///
255 /// let node = Node::new_alloc();
256 /// if node.has_node(name.arg()) {
257 /// // ...
258 /// }
259 /// ```
260 }
261
262 #[doc(hidden)]
263 pub fn as_inner(&self) -> inner::InnerString<'_> {
264 inner::InnerString::from_outer(self)
265 }
266}
267
268// SAFETY:
269// - `move_return_ptr`
270// Nothing special needs to be done beyond a `std::mem::swap` when returning a String.
271// So we can just use `ffi_methods`.
272//
273// - `from_arg_ptr`
274// Strings are properly initialized through a `from_sys` call, but the ref-count should be
275// incremented as that is the callee's responsibility. Which we do by calling
276// `std::mem::forget(string.clone())`.
277unsafe impl GodotFfi for GString {
278 const VARIANT_TYPE: ExtVariantType = ExtVariantType::Concrete(sys::VariantType::STRING);
279
280 ffi_methods! { type sys::GDExtensionTypePtr = *mut Self; .. }
281}
282
283meta::impl_godot_as_self!(GString);
284
285impl_builtin_traits! {
286 for GString {
287 Default => string_construct_default;
288 Clone => string_construct_copy;
289 Drop => string_destroy;
290 Eq => string_operator_equal;
291 Ord => string_operator_less;
292 Hash;
293 }
294}
295
296impl_shared_string_api! {
297 builtin: GString,
298 find_builder: ExGStringFind,
299 split_builder: ExGStringSplit,
300}
301
302impl fmt::Display for GString {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 pad_if_needed(f, |f| {
305 for ch in self.chars() {
306 f.write_char(*ch)?;
307 }
308
309 Ok(())
310 })
311 }
312}
313
314/// Uses literal syntax from GDScript: `"string"`
315impl fmt::Debug for GString {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 // Reuse Display impl.
318 write!(f, "\"{self}\"")
319 }
320}
321
322// ----------------------------------------------------------------------------------------------------------------------------------------------
323// Conversion from/into Rust string-types
324
325impl From<&str> for GString {
326 fn from(s: &str) -> Self {
327 let bytes = s.as_bytes();
328
329 unsafe {
330 Self::new_with_string_uninit(|string_ptr| {
331 let ctor = interface_fn!(string_new_with_utf8_chars_and_len);
332 ctor(
333 string_ptr,
334 bytes.as_ptr() as *const std::ffi::c_char,
335 bytes.len() as i64,
336 );
337 })
338 }
339 }
340}
341
342impl From<&[char]> for GString {
343 fn from(chars: &[char]) -> Self {
344 // SAFETY: A `char` value is by definition a valid Unicode code point.
345 unsafe {
346 Self::new_with_string_uninit(|string_ptr| {
347 let ctor = interface_fn!(string_new_with_utf32_chars_and_len);
348 ctor(
349 string_ptr,
350 chars.as_ptr() as *const sys::char32_t,
351 chars.len() as i64,
352 );
353 })
354 }
355 }
356}
357
358impl From<String> for GString {
359 fn from(value: String) -> Self {
360 value.as_str().into()
361 }
362}
363
364impl From<&String> for GString {
365 fn from(value: &String) -> Self {
366 value.as_str().into()
367 }
368}
369
370impl From<&GString> for String {
371 fn from(string: &GString) -> Self {
372 unsafe {
373 let len =
374 interface_fn!(string_to_utf8_chars)(string.string_sys(), std::ptr::null_mut(), 0);
375
376 assert!(len >= 0);
377 let mut buf = vec![0u8; len as usize];
378
379 interface_fn!(string_to_utf8_chars)(
380 string.string_sys(),
381 buf.as_mut_ptr() as *mut std::ffi::c_char,
382 len,
383 );
384
385 // Note: could use from_utf8_unchecked() but for now prefer safety
386 String::from_utf8(buf).expect("String::from_utf8")
387 }
388 }
389}
390
391impl From<GString> for String {
392 /// Converts this `GString` to a `String`.
393 ///
394 /// This is identical to `String::from(&string)`, and as such there is no performance benefit.
395 fn from(string: GString) -> Self {
396 Self::from(&string)
397 }
398}
399
400impl std::str::FromStr for GString {
401 type Err = Infallible;
402
403 fn from_str(s: &str) -> Result<Self, Self::Err> {
404 Ok(Self::from(s))
405 }
406}
407
408// ----------------------------------------------------------------------------------------------------------------------------------------------
409// Conversion from other Godot string-types
410
411impl From<&StringName> for GString {
412 fn from(string: &StringName) -> Self {
413 unsafe {
414 Self::new_with_uninit(|self_ptr| {
415 let ctor = sys::builtin_fn!(string_from_string_name);
416 let args = [string.sys()];
417 ctor(self_ptr, args.as_ptr());
418 })
419 }
420 }
421}
422
423impl From<StringName> for GString {
424 /// Converts this `StringName` to a `GString`.
425 ///
426 /// This is identical to `GString::from(&string_name)`, and as such there is no performance benefit.
427 fn from(string_name: StringName) -> Self {
428 Self::from(&string_name)
429 }
430}
431
432impl From<&NodePath> for GString {
433 fn from(path: &NodePath) -> Self {
434 unsafe {
435 Self::new_with_uninit(|self_ptr| {
436 let ctor = sys::builtin_fn!(string_from_node_path);
437 let args = [path.sys()];
438 ctor(self_ptr, args.as_ptr());
439 })
440 }
441 }
442}
443
444impl From<NodePath> for GString {
445 /// Converts this `NodePath` to a `GString`.
446 ///
447 /// This is identical to `GString::from(&path)`, and as such there is no performance benefit.
448 fn from(path: NodePath) -> Self {
449 Self::from(&path)
450 }
451}
452
453#[cfg(feature = "serde")] #[cfg_attr(published_docs, doc(cfg(feature = "serde")))]
454mod serialize {
455 use std::fmt::Formatter;
456
457 use serde::de::{Error, Visitor};
458 use serde::{Deserialize, Deserializer, Serialize, Serializer};
459
460 use super::*;
461
462 // For "Available on crate feature `serde`" in docs. Cannot be inherited from module. Also does not support #[derive] (e.g. in Vector2).
463 #[cfg_attr(published_docs, doc(cfg(feature = "serde")))]
464 impl Serialize for GString {
465 #[inline]
466 fn serialize<S>(
467 &self,
468 serializer: S,
469 ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
470 where
471 S: Serializer,
472 {
473 serializer.serialize_str(&self.to_string())
474 }
475 }
476
477 #[cfg_attr(published_docs, doc(cfg(feature = "serde")))]
478 impl<'de> Deserialize<'de> for GString {
479 #[inline]
480 fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
481 where
482 D: Deserializer<'de>,
483 {
484 struct GStringVisitor;
485 impl Visitor<'_> for GStringVisitor {
486 type Value = GString;
487
488 fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
489 formatter.write_str("a GString")
490 }
491
492 fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
493 where
494 E: Error,
495 {
496 Ok(GString::from(s))
497 }
498 }
499
500 deserializer.deserialize_str(GStringVisitor)
501 }
502 }
503}