From 336743738e61c3eb2e611f189435ec3240d5f6d2 Mon Sep 17 00:00:00 2001 From: _cry64 Date: Fri, 27 Mar 2026 11:19:06 +1000 Subject: [PATCH] add AsCPtr trait --- nixide/src/stdext/cchar_ptr_ext.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/nixide/src/stdext/cchar_ptr_ext.rs b/nixide/src/stdext/cchar_ptr_ext.rs index 5d506a9..733ed98 100644 --- a/nixide/src/stdext/cchar_ptr_ext.rs +++ b/nixide/src/stdext/cchar_ptr_ext.rs @@ -5,6 +5,31 @@ use std::str::from_utf8; use crate::errors::new_nixide_error; use crate::NixideResult; +pub trait AsCPtr { + fn as_c_ptr(&self) -> NixideResult<*const T>; + + fn into_c_ptr(self) -> NixideResult<*mut T>; +} + +impl AsCPtr for T +where + T: AsRef, +{ + fn as_c_ptr(&self) -> NixideResult<*const c_char> { + match CStr::from_bytes_until_nul(self.as_ref().as_bytes()) { + Ok(s) => Ok(s.as_ptr()), + Err(_) => Err(new_nixide_error!(StringNulByte)), + } + } + + fn into_c_ptr(self) -> NixideResult<*mut c_char> { + match CStr::from_bytes_until_nul(self.as_ref().as_bytes()) { + Ok(s) => Ok(s.as_ptr().cast_mut()), + Err(_) => Err(new_nixide_error!(StringNulByte)), + } + } +} + pub trait CCharPtrExt { fn to_utf8_string(self) -> NixideResult;