Skip to content

Commit 73c29da

Browse files
committed
glib: make some GStr methods const
1 parent 93ae903 commit 73c29da

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

glib/src/gstring.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ impl GStr {
149149
/// This function is the equivalent of [`GStr::to_bytes`] except that it will retain the
150150
/// trailing nul terminator instead of chopping it off.
151151
#[inline]
152-
pub fn as_bytes_with_nul(&self) -> &[u8] {
152+
pub const fn as_bytes_with_nul(&self) -> &[u8] {
153153
self.0.as_bytes()
154154
}
155155
// rustdoc-stripper-ignore-next
@@ -158,7 +158,7 @@ impl GStr {
158158
/// The returned slice will **not** contain the trailing nul terminator that this GLib
159159
/// string has.
160160
#[inline]
161-
pub fn as_bytes(&self) -> &[u8] {
161+
pub const fn as_bytes(&self) -> &[u8] {
162162
self.as_str().as_bytes()
163163
}
164164
// rustdoc-stripper-ignore-next
@@ -173,15 +173,20 @@ impl GStr {
173173
/// writes to it) causes undefined behavior. It is your responsibility to make
174174
/// sure that the underlying memory is not freed too early.
175175
#[inline]
176-
pub fn as_ptr(&self) -> *const c_char {
176+
pub const fn as_ptr(&self) -> *const c_char {
177177
self.0.as_ptr() as *const _
178178
}
179179
// rustdoc-stripper-ignore-next
180180
/// Converts this GLib string to a string slice.
181181
#[inline]
182-
pub fn as_str(&self) -> &str {
182+
pub const fn as_str(&self) -> &str {
183183
// Clip off the nul-byte
184-
unsafe { self.0.get_unchecked(..self.0.len() - 1) }
184+
unsafe {
185+
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
186+
self.as_ptr() as *const _,
187+
self.0.len() - 1,
188+
))
189+
}
185190
}
186191
// rustdoc-stripper-ignore-next
187192
/// Converts this GLib string to a C string slice, checking for interior nul-bytes.
@@ -208,7 +213,7 @@ impl GStr {
208213
/// `self` **must** not contain any interior nul-bytes besides the final terminating nul-byte.
209214
/// It is undefined behavior to call this on a string that contains interior nul-bytes.
210215
#[inline]
211-
pub unsafe fn to_cstr_unchecked(&self) -> &CStr {
216+
pub const unsafe fn to_cstr_unchecked(&self) -> &CStr {
212217
CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul())
213218
}
214219

0 commit comments

Comments
 (0)