Skip to content

Commit fe8cab7

Browse files
jf2048sdroege
authored andcommitted
glib: add GStr::from_ptr_checked()
For performing utf-8 checks on a pointer.
1 parent 8e031e2 commit fe8cab7

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

glib/src/gstring.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -144,16 +144,29 @@ impl GStr {
144144
/// Wraps a raw C string with a safe GLib string wrapper. The provided C string **must** be
145145
/// nul-terminated. All constraints from [`std::ffi::CStr::from_ptr`] also apply here.
146146
///
147-
/// If the string is valid UTF-8 then it is directly returned otherwise a copy is created with
148-
/// every invalid character replaced by the Unicode replacement character (U+FFFD).
147+
/// If the string is valid UTF-8 then it is directly returned, otherwise `None` is returned.
149148
#[inline]
150-
pub unsafe fn from_ptr_lossy<'a>(ptr: *const c_char) -> Cow<'a, Self> {
149+
pub unsafe fn from_ptr_checked<'a>(ptr: *const c_char) -> Option<&'a Self> {
151150
let mut end_ptr = ptr::null();
152151
if ffi::g_utf8_validate(ptr as *const _, -1, &mut end_ptr) != ffi::GFALSE {
153-
Cow::Borrowed(Self::from_utf8_with_nul_unchecked(slice::from_raw_parts(
152+
Some(Self::from_utf8_with_nul_unchecked(slice::from_raw_parts(
154153
ptr as *const u8,
155154
end_ptr.offset_from(ptr) as usize + 1,
156155
)))
156+
} else {
157+
None
158+
}
159+
}
160+
// rustdoc-stripper-ignore-next
161+
/// Wraps a raw C string with a safe GLib string wrapper. The provided C string **must** be
162+
/// nul-terminated. All constraints from [`std::ffi::CStr::from_ptr`] also apply here.
163+
///
164+
/// If the string is valid UTF-8 then it is directly returned otherwise a copy is created with
165+
/// every invalid character replaced by the Unicode replacement character (U+FFFD).
166+
#[inline]
167+
pub unsafe fn from_ptr_lossy<'a>(ptr: *const c_char) -> Cow<'a, Self> {
168+
if let Some(gs) = Self::from_ptr_checked(ptr) {
169+
Cow::Borrowed(gs)
157170
} else {
158171
Cow::Owned(GString::from_glib_full(ffi::g_utf8_make_valid(
159172
ptr as *const _,

0 commit comments

Comments
 (0)