Skip to main content

duckdb/types/
string.rs

1use libduckdb_sys::{duckdb_string_t, duckdb_string_t_data, duckdb_string_t_length};
2
3/// Wrapper for underlying duck string type with a lifetime bound to a &mut duckdb_string_t
4pub struct DuckString<'a> {
5    ptr: &'a mut duckdb_string_t,
6}
7
8impl<'a> DuckString<'a> {
9    /// Creates a DuckString from the underlying duck string type
10    pub fn new(ptr: &'a mut duckdb_string_t) -> Self {
11        DuckString { ptr }
12    }
13}
14
15impl<'a> DuckString<'a> {
16    /// convert duckdb_string_t to a copy on write string
17    pub fn as_str(&mut self) -> std::borrow::Cow<'a, str> {
18        String::from_utf8_lossy(self.as_bytes())
19    }
20
21    /// convert duckdb_string_t to a byte slice
22    pub fn as_bytes(&mut self) -> &'a [u8] {
23        unsafe {
24            let len = duckdb_string_t_length(*self.ptr);
25            let c_ptr = duckdb_string_t_data(self.ptr);
26            std::slice::from_raw_parts(c_ptr as *const u8, len as usize)
27        }
28    }
29}