commonlibsse_ng\re\h/
hkStringPtr.rs

1//! # hkStringPtr
2//!
3//! This module defines the `hkStringPtr` struct, representing a managed string pointer
4//! in the Havok engine. It includes methods for string access, capacity checking, and
5//! compatibility with C++ memory layout.
6
7use core::ffi::{CStr, c_char};
8use core::mem;
9use core::ptr;
10
11/// Represents a managed string pointer in the Havok engine.
12#[repr(C)]
13#[derive(Debug)]
14pub struct hkStringPtr {
15    /// Pointer to the string data.
16    /// - Offset: `0x0`
17    pub _data: *const c_char,
18}
19
20/// Ensure the memory layout matches the C++ version.
21const _: () = {
22    assert!(mem::size_of::<hkStringPtr>() == 0x8);
23    assert!(mem::align_of::<hkStringPtr>() == mem::align_of::<*const c_char>());
24};
25
26impl hkStringPtr {
27    /// Managed flag mask.
28    const MANAGED: usize = 1 << 0;
29
30    /// Creates a new `hkStringPtr` with the given string data.
31    ///
32    /// # Arguments
33    /// - `data`: The C string pointer.
34    ///
35    /// # Returns
36    /// - `hkStringPtr` instance.
37    #[inline]
38    pub const fn new(data: *const c_char) -> Self {
39        Self { _data: data }
40    }
41
42    /// Returns the raw string data, removing the managed flag.
43    ///
44    /// # Returns
45    /// - `*const c_char`: Pointer to the string data.
46    #[inline]
47    pub fn as_ptr(&self) -> *const c_char {
48        (self._data as usize & !Self::MANAGED) as *const c_char
49    }
50
51    /// Returns the C-style string.
52    ///
53    /// # Returns
54    /// - `&CStr`: Reference to the string data.
55    #[inline]
56    pub fn as_c_str(&self) -> &CStr {
57        unsafe { CStr::from_ptr(self.as_ptr()) }
58    }
59
60    /// Checks if the string is empty.
61    ///
62    /// - C++: `empty`
63    ///
64    /// # Returns
65    /// - `bool`: `true` if empty, otherwise `false`.
66    #[inline]
67    pub fn is_empty(&self) -> bool {
68        self._data.is_null() || unsafe { *self.as_ptr() == 0 }
69    }
70
71    /// Returns the size of the string.
72    ///
73    /// - C++: Equivalent `size()`/`length()` method
74    ///
75    /// # Returns
76    /// - `i32`: Length of the string.
77    #[inline]
78    pub fn len(&self) -> usize {
79        if self.is_empty() { 0 } else { unsafe { CStr::from_ptr(self._data).count_bytes() } }
80    }
81}
82
83impl Default for hkStringPtr {
84    #[inline]
85    fn default() -> Self {
86        Self::new(ptr::null())
87    }
88}