Skip to content

Commit 6e76ebb

Browse files
committed
glib: GStringBuilder by construction always returns an UTF-8 string and never a NULL pointer
1 parent 932f275 commit 6e76ebb

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

glib/src/gstring.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,21 @@ impl GString {
440440
pub unsafe fn from_ptr_lossy<'a>(ptr: *const c_char) -> Cow<'a, GStr> {
441441
GStr::from_ptr_lossy(ptr)
442442
}
443+
444+
// rustdoc-stripper-ignore-next
445+
/// Wraps a raw C string with a safe GLib string wrapper. The provided C string **must** be
446+
/// nul-terminated. All constraints from [`std::ffi::CStr::from_ptr`] also apply here.
447+
///
448+
/// `len` is the length without the nul-terminator, i.e. if `len == 0` is passed then `*ptr`
449+
/// must be the nul-terminator.
450+
pub unsafe fn from_ptr_and_len_unchecked(ptr: *const c_char, len: usize) -> Self {
451+
assert!(!ptr.is_null());
452+
453+
GString(Inner::Foreign {
454+
ptr: ptr::NonNull::new_unchecked(ptr as *mut _),
455+
len,
456+
})
457+
}
443458
}
444459

445460
impl IntoGlibPtr<*mut c_char> for GString {

glib/src/gstring_builder.rs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,6 @@ impl GStringBuilder {
116116

117117
// rustdoc-stripper-ignore-next
118118
/// Returns `&str` slice.
119-
///
120-
/// # Panics
121-
///
122-
/// If the string builder contains invalid UTF-8 this function panics.
123119
pub fn as_str(&self) -> &str {
124120
unsafe {
125121
let ptr: *const u8 = self.inner.str as _;
@@ -128,21 +124,17 @@ impl GStringBuilder {
128124
return "";
129125
}
130126
let slice = slice::from_raw_parts(ptr, len);
131-
std::str::from_utf8(slice).unwrap()
127+
std::str::from_utf8_unchecked(slice)
132128
}
133129
}
134130

135131
// rustdoc-stripper-ignore-next
136132
/// Returns `&str` slice.
137-
///
138-
/// # Panics
139-
///
140-
/// If the string builder contains invalid UTF-8 this function panics.
141133
#[must_use = "String returned from the builder should probably be used"]
142134
pub fn into_string(self) -> crate::GString {
143135
unsafe {
144136
let s = mem::ManuallyDrop::new(self);
145-
crate::GString::from_glib_full_num(s.inner.str, s.inner.len)
137+
crate::GString::from_ptr_and_len_unchecked(s.inner.str, s.inner.len)
146138
}
147139
}
148140
}

0 commit comments

Comments
 (0)