|
| 1 | +use std::{ |
| 2 | + ffi::{c_char, CStr}, |
| 3 | + ops::Deref, |
| 4 | +}; |
| 5 | + |
| 6 | +use crate::duckdb_free; |
| 7 | + |
| 8 | +pub struct DuckDbString { |
| 9 | + // Invariant: ptr[0..len+1] is valid C string, i.e. ptr[len] is NUL byte. |
| 10 | + ptr: core::ptr::NonNull<c_char>, |
| 11 | + len: usize, |
| 12 | +} |
| 13 | + |
| 14 | +impl DuckDbString { |
| 15 | + /// Creates a `DuckDbString` from a raw pointer to a C string. |
| 16 | + /// |
| 17 | + /// # Safety |
| 18 | + /// |
| 19 | + /// The caller must ensure that the pointer is valid and points to a null-terminated C string. |
| 20 | + /// The memory must remain valid for the lifetime of the returned `DuckDbString`. |
| 21 | + pub unsafe fn from_ptr(ptr: *const c_char) -> Self { |
| 22 | + let len = unsafe { CStr::from_ptr(ptr) }.to_bytes().len(); |
| 23 | + unsafe { Self::from_raw_parts(ptr, len) } |
| 24 | + } |
| 25 | + |
| 26 | + /// Creates a `DuckDbString` from raw parts. |
| 27 | + /// |
| 28 | + /// # Safety |
| 29 | + /// |
| 30 | + /// The caller must ensure that: |
| 31 | + /// - `ptr` is a valid pointer to a null-terminated C string. |
| 32 | + /// - `len` accurately represents the length of the string (excluding the null terminator). |
| 33 | + /// - The memory referenced by `ptr` remains valid for the lifetime of the returned `DuckDbString`. |
| 34 | + /// - The string data is not mutated for the lifetime of the returned `DuckDbString`. |
| 35 | + pub unsafe fn from_raw_parts(ptr: *const c_char, len: usize) -> Self { |
| 36 | + let ptr = unsafe { core::ptr::NonNull::new_unchecked(ptr as *mut c_char) }; |
| 37 | + Self { ptr, len } |
| 38 | + } |
| 39 | + |
| 40 | + fn to_bytes_with_nul(&self) -> &[u8] { |
| 41 | + let ptr = self.ptr.as_ptr() as *const u8; |
| 42 | + unsafe { core::slice::from_raw_parts(ptr, self.len + 1) } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl Deref for DuckDbString { |
| 47 | + type Target = std::ffi::CStr; |
| 48 | + |
| 49 | + fn deref(&self) -> &Self::Target { |
| 50 | + let bytes = self.to_bytes_with_nul(); |
| 51 | + unsafe { CStr::from_bytes_with_nul_unchecked(bytes) } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl Drop for DuckDbString { |
| 56 | + fn drop(&mut self) { |
| 57 | + let ptr = self.ptr.as_ptr() as *mut core::ffi::c_void; |
| 58 | + unsafe { duckdb_free(ptr) }; |
| 59 | + } |
| 60 | +} |
0 commit comments