1use std::{
2 ffi::{c_char, CStr},
3 ops::Deref,
4};
5
6use crate::duckdb_free;
7
8pub struct DuckDbString {
9 ptr: core::ptr::NonNull<c_char>,
11 len: usize,
12}
13
14impl DuckDbString {
15 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 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
46impl 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
55impl 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}