summary refs log tree commit diff stats
path: root/src/impls/cstr.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/impls/cstr.rs')
-rw-r--r--src/impls/cstr.rs64
1 files changed, 64 insertions, 0 deletions
diff --git a/src/impls/cstr.rs b/src/impls/cstr.rs
index 5467963..700ae13 100644
--- a/src/impls/cstr.rs
+++ b/src/impls/cstr.rs
@@ -4,15 +4,79 @@ use std::os::raw::c_char;
 
 use crate::*;
 
+/// Conversion from [`CStr`] to [`ConstLtPtr`].
 impl AsLtPtr for CStr {
+    /// The target type of this conversion.
     type Target = c_char;
 
     /// Returns the inner pointer to this C string.
     ///
     /// The returned pointer points to a contiguous region of memory terminated
     /// with a 0 byte to represent the end of the string.
+    ///
+    /// # Examples
+    ///
+    /// `ltptr` protects you from dangling pointers: (adapted from
+    /// [`CStr::as_ptr`])
+    ///
+    /// ```rust compile_fail
+    /// use std::ffi::CString;
+    /// use ltptr::AsLtPtr;
+    ///
+    /// let ptr = CString::new("Hello").unwrap().as_lt_ptr();
+    /// unsafe {
+    ///     // would be dangling but the compiler prevents this from compiling
+    ///     ptr.as_raw();
+    /// }
+    /// ```
+    ///
+    /// Which you can fix by adding a binding:
+    ///
+    /// ```rust
+    /// use std::ffi::CString;
+    /// use ltptr::AsLtPtr;
+    ///
+    /// let hello = CString::new("Hello").unwrap();
+    /// let ptr = hello.as_lt_ptr();
+    /// unsafe {
+    ///     // perfectly fine
+    ///     ptr.as_raw();
+    /// }
+    /// ```
     #[inline]
     fn as_lt_ptr(&self) -> ConstLtPtr<'_, c_char> {
         unsafe { ConstLtPtr::from_raw(self.as_ptr()) }
     }
 }
+
+/// Conversion from [`ConstLtPtr`] of [`c_char`] to [`CStr`].
+impl FromLtPtr<c_char> for CStr {
+    /// Wraps a raw C string with a safe C string wrapper.
+    ///
+    /// # Safety
+    ///
+    /// See [`CStr::from_ptr`] for the safety requirements.
+    ///
+    /// # Examples
+    ///
+    /// ```rust
+    /// use std::ffi::CStr;
+    /// use std::ffi::CString;
+    /// use std::os::raw::c_char;
+    /// use ltptr::AsLtPtr;
+    /// use ltptr::ConstLtPtr;
+    /// use ltptr::FromLtPtr;
+    ///
+    /// unsafe fn foo(ptr: ConstLtPtr<'_, c_char>) {
+    ///     let first = unsafe { CStr::from_lt_ptr(ptr) }.to_str().to_owned();
+    /// }
+    ///
+    /// let hello = CString::new("Hello").unwrap();
+    /// let ptr = hello.as_lt_ptr();
+    /// unsafe { foo(ptr) };
+    /// ```
+    #[inline]
+    unsafe fn from_lt_ptr(ptr: ConstLtPtr<'_, c_char>) -> &CStr {
+        unsafe { CStr::from_ptr(ptr.as_raw()) }
+    }
+}