Skip to content

Commit 0c15b29

Browse files
jf2048sdroege
authored andcommitted
glib: make some GStr methods const
1 parent a577a12 commit 0c15b29

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
@@ -168,7 +168,7 @@ impl GStr {
168168
/// This function is the equivalent of [`GStr::to_bytes`] except that it will retain the
169169
/// trailing nul terminator instead of chopping it off.
170170
#[inline]
171-
pub fn as_bytes_with_nul(&self) -> &[u8] {
171+
pub const fn as_bytes_with_nul(&self) -> &[u8] {
172172
self.0.as_bytes()
173173
}
174174
// rustdoc-stripper-ignore-next
@@ -177,7 +177,7 @@ impl GStr {
177177
/// The returned slice will **not** contain the trailing nul terminator that this GLib
178178
/// string has.
179179
#[inline]
180-
pub fn as_bytes(&self) -> &[u8] {
180+
pub const fn as_bytes(&self) -> &[u8] {
181181
self.as_str().as_bytes()
182182
}
183183
// rustdoc-stripper-ignore-next
@@ -192,15 +192,20 @@ impl GStr {
192192
/// writes to it) causes undefined behavior. It is your responsibility to make
193193
/// sure that the underlying memory is not freed too early.
194194
#[inline]
195-
pub fn as_ptr(&self) -> *const c_char {
195+
pub const fn as_ptr(&self) -> *const c_char {
196196
self.0.as_ptr() as *const _
197197
}
198198
// rustdoc-stripper-ignore-next
199199
/// Converts this GLib string to a string slice.
200200
#[inline]
201-
pub fn as_str(&self) -> &str {
201+
pub const fn as_str(&self) -> &str {
202202
// Clip off the nul-byte
203-
unsafe { self.0.get_unchecked(..self.0.len() - 1) }
203+
unsafe {
204+
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
205+
self.as_ptr() as *const _,
206+
self.0.len() - 1,
207+
))
208+
}
204209
}
205210
// rustdoc-stripper-ignore-next
206211
/// Converts this GLib string to a C string slice, checking for interior nul-bytes.
@@ -227,7 +232,7 @@ impl GStr {
227232
/// `self` **must** not contain any interior nul-bytes besides the final terminating nul-byte.
228233
/// It is undefined behavior to call this on a string that contains interior nul-bytes.
229234
#[inline]
230-
pub unsafe fn to_cstr_unchecked(&self) -> &CStr {
235+
pub const unsafe fn to_cstr_unchecked(&self) -> &CStr {
231236
CStr::from_bytes_with_nul_unchecked(self.as_bytes_with_nul())
232237
}
233238

0 commit comments

Comments
 (0)