Skip to content

Commit 6e634ec

Browse files
Use CStr and CString because BorrowDatum is not impled for str
1 parent 8619107 commit 6e634ec

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

pgrx-tests/src/tests/borrow_datum.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ mod tests {
6060
use super::*;
6161
#[allow(unused)]
6262
use crate as pgrx_tests;
63+
use std::ffi::{CStr, CString};
6364

6465
// Exercising BorrowDatum impls
6566
clonetrip!(clone_bool, test_clone_bool, &'a bool, &false);
@@ -73,7 +74,7 @@ mod tests {
7374
&'a pg_sys::Point,
7475
&pg_sys::Point { x: -1.0, y: f64::INFINITY }
7576
);
76-
clonetrip!(clone_str, test_clone_str, &'a str => String, "string", String::from("string"));
77+
clonetrip!(clone_str, test_clone_str, &'a CStr => CString, c"cee string", CString::from(c"cee string"));
7778
clonetrip!(
7879
clone_oid,
7980
test_clone_oid,

pgrx/src/datum/from.rs

+28
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use crate::{
1313
pg_sys, varlena, varlena_to_byte_slice, AllocatedByPostgres, IntoDatum, PgBox, PgMemoryContexts,
1414
};
15+
use alloc::ffi::CString;
1516
use core::{ffi::CStr, mem::size_of};
1617
use std::num::NonZeroUsize;
1718

@@ -482,6 +483,33 @@ impl<'a> FromDatum for &'a core::ffi::CStr {
482483
}
483484
}
484485

486+
impl FromDatum for alloc::ffi::CString {
487+
#[inline]
488+
unsafe fn from_polymorphic_datum(
489+
datum: pg_sys::Datum,
490+
is_null: bool,
491+
_: pg_sys::Oid,
492+
) -> Option<CString> {
493+
if is_null || datum.is_null() {
494+
None
495+
} else {
496+
Some(core::ffi::CStr::from_ptr(datum.cast_mut_ptr()).to_owned())
497+
}
498+
}
499+
500+
unsafe fn from_datum_in_memory_context(
501+
_memory_context: PgMemoryContexts,
502+
datum: pg_sys::Datum,
503+
is_null: bool,
504+
_typoid: pg_sys::Oid,
505+
) -> Option<Self>
506+
where
507+
Self: Sized,
508+
{
509+
Self::from_polymorphic_datum(datum, is_null, _typoid)
510+
}
511+
}
512+
485513
/// for bytea
486514
impl<'a> FromDatum for &'a [u8] {
487515
#[inline]

0 commit comments

Comments
 (0)