spirv_cross2/string.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
use crate::cell::AllocationDropGuard;
use crate::SpirvCrossError;
use std::borrow::Cow;
use std::ffi::{c_char, CStr, CString};
use std::fmt::{Debug, Display, Formatter};
use std::ops::Deref;
/// An immutable wrapper around a valid UTF-8 string whose memory contents
/// may or may not be originating from FFI.
///
/// In most cases, users of this library do not need to worry about
/// constructing a [`CompilerStr`]. All functions that take strings
/// take `impl Into<CompilerStr<'_>>`, which converts automatically from
/// [`&str`](str) and [`String`](String).
///
/// [`CompilerStr`] also implements [`Deref`](Deref) for [`&str`](str),
/// so all immutable `str` methods are available.
///
/// # Allocation Behaviour
/// If the string originated from FFI and is a valid nul-terminated
/// C string, then the pointer to the string will be saved,
/// such that when being read by FFI there are no extra allocations
/// required.
///
/// If the provenance of the string is a `&str` with lifetime longer than `'a`,
/// then an allocation will occur when passing the string to FFI.
///
/// If the provenance of the string is an owned Rust `String`, then an allocation
/// will occur only if necessary to append a nul byte.
///
/// If the provenance of the string is a `&CStr`, or
/// with lifetime longer than `'a`, then an allocation will not occur
/// when passing the string to FFI.
///
/// Using [C-string literals](https://doc.rust-lang.org/edition-guide/rust-2021/c-string-literals.html)
/// where possible can be used to avoid an allocation.
pub struct CompilerStr<'a> {
pointer: Option<ContextPointer<'a>>,
cow: Cow<'a, str>,
}
// SAFETY: SpirvCrossContext is Send.
// Once created, the ContextStr is immutable, so it is also sync.
// cloning the string doesn't affect the memory, as long as it
// is alive for 'a.
//
// There is no interior mutability of a
unsafe impl Send for CompilerStr<'_> {}
unsafe impl Sync for CompilerStr<'_> {}
impl Clone for CompilerStr<'_> {
fn clone(&self) -> Self {
Self {
pointer: self.pointer.clone(),
cow: self.cow.clone(),
}
}
}
pub(crate) enum ContextPointer<'a> {
FromContext {
// the lifetime of pointer should be 'a.
pointer: *const c_char,
context: AllocationDropGuard,
},
BorrowedCStr(&'a CStr),
}
impl ContextPointer<'_> {
pub const fn pointer(&self) -> *const c_char {
match self {
ContextPointer::FromContext { pointer, .. } => *pointer,
ContextPointer::BorrowedCStr(cstr) => cstr.as_ptr(),
}
}
}
impl Clone for ContextPointer<'_> {
fn clone(&self) -> Self {
match self {
ContextPointer::FromContext { pointer, context } => ContextPointer::FromContext {
pointer: pointer.clone(),
context: context.clone(),
},
ContextPointer::BorrowedCStr(cstr) => ContextPointer::BorrowedCStr(*cstr),
}
}
}
impl<'a> Display for CompilerStr<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.cow)
}
}
impl<'a> Debug for CompilerStr<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.cow)
}
}
pub(crate) enum MaybeOwnedCString<'a> {
Owned(CString),
Borrowed(ContextPointer<'a>),
}
impl MaybeOwnedCString<'_> {
/// Get a pointer to the C string.
///
/// The pointer will be valid for the lifetime of `self`.
pub fn as_ptr(&self) -> *const c_char {
match self {
MaybeOwnedCString::Owned(c) => c.as_ptr(),
MaybeOwnedCString::Borrowed(ptr) => ptr.pointer(),
}
}
}
impl AsRef<str> for CompilerStr<'_> {
fn as_ref(&self) -> &str {
self.cow.as_ref()
}
}
impl Deref for CompilerStr<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.cow.deref()
}
}
impl PartialEq for CompilerStr<'_> {
fn eq(&self, other: &CompilerStr<'_>) -> bool {
self.cow.eq(&other.cow)
}
}
impl<'a> PartialEq<&'a str> for CompilerStr<'_> {
fn eq(&self, other: &&'a str) -> bool {
self.cow.eq(other)
}
}
impl<'a> PartialEq<CompilerStr<'_>> for &'a str {
fn eq(&self, other: &CompilerStr<'_>) -> bool {
self.eq(&other.cow)
}
}
impl PartialEq<str> for CompilerStr<'_> {
fn eq(&self, other: &str) -> bool {
self.cow.eq(other)
}
}
impl PartialEq<CompilerStr<'_>> for str {
fn eq(&self, other: &CompilerStr<'_>) -> bool {
self.eq(&other.cow)
}
}
impl PartialEq<CompilerStr<'_>> for String {
fn eq(&self, other: &CompilerStr<'_>) -> bool {
self.eq(&other.cow)
}
}
impl PartialEq<String> for CompilerStr<'_> {
fn eq(&self, other: &String) -> bool {
self.cow.eq(other)
}
}
impl Eq for CompilerStr<'_> {}
impl From<String> for CompilerStr<'_> {
fn from(value: String) -> Self {
Self::from_string(value)
}
}
impl<'a> From<&'a str> for CompilerStr<'a> {
fn from(value: &'a str) -> Self {
Self::from_str(value)
}
}
impl<'a> From<&'a CStr> for CompilerStr<'a> {
fn from(value: &'a CStr) -> Self {
Self::from_cstr(value)
}
}
/// # Safety
/// Returning `ContextStr<'a>` where `'a` is the lifetime of the
/// [`SpirvCrossContext`](crate::SpirvCrossContext) is only correct if the
/// string is borrow-owned by the context.
///
/// In most cases, the returned lifetime should be the lifetime of the mutable borrow,
/// if returning a string from the [`Compiler`](crate::Compiler).
///
/// [`CompilerStr::from_ptr`] takes a context argument, and the context must be
/// the source of provenance for the `ContextStr`.
impl<'a> CompilerStr<'a> {
/// Wraps a raw C string with a safe C string wrapper.
///
/// If the raw C string is valid UTF-8, a pointer to the string will be
/// kept around, which can be passed back to C at zero cost.
///
/// # Safety
///
/// * The memory pointed to by `ptr` must contain a valid nul terminator at the
/// end of the string.
///
/// * `ptr` must be valid for reads of bytes up to and including the nul terminator.
/// This means in particular:
///
/// * The entire memory range of this `CStr` must be contained within a single allocated object!
/// * `ptr` must be non-null even for a zero-length cstr.
///
/// * The memory referenced by the returned `CStr` must not be mutated for
/// the duration of lifetime `'a`.
///
/// * The nul terminator must be within `isize::MAX` from `ptr`
///
/// * The memory pointed to by `ptr` must be valid for the duration of the lifetime `'a`.
///
/// * THe provenance of `context.ptr` must be a superset of `ptr`.
/// # Caveat
///
/// The lifetime for the returned slice is inferred from its usage. To prevent accidental misuse,
/// it's suggested to tie the lifetime to whichever source lifetime is safe in the context,
/// such as by providing a helper function taking the lifetime of a host value for the slice,
/// or by explicit annotation.
pub(crate) unsafe fn from_ptr<'b>(
ptr: *const c_char,
arena: AllocationDropGuard,
) -> CompilerStr<'b>
where
'a: 'b,
{
let cstr = CStr::from_ptr(ptr);
let maybe = cstr.to_string_lossy();
if matches!(&maybe, &Cow::Borrowed(_)) {
Self {
pointer: Some(ContextPointer::FromContext {
pointer: ptr,
context: arena,
}),
cow: maybe,
}
} else {
Self {
pointer: None,
cow: maybe,
}
}
}
/// Wrap a Rust `&str`.
///
/// This will allocate when exposing to C.
pub(crate) fn from_str(str: &'a str) -> Self {
Self {
pointer: None,
cow: Cow::Borrowed(str),
}
}
/// Wrap a Rust `String`.
///
/// This will allocate when exposing to C.
pub(crate) fn from_string(str: String) -> Self {
Self {
pointer: None,
cow: Cow::Owned(str),
}
}
pub(crate) fn from_cstr(cstr: &'a CStr) -> Self {
Self {
pointer: Some(ContextPointer::BorrowedCStr(cstr)),
cow: cstr.to_string_lossy(),
}
}
/// Allocate if necessary, if not then return a pointer to the original cstring.
///
/// The returned pointer will be valid for the lifetime `'a`.
pub(crate) fn into_cstring_ptr(self) -> Result<MaybeOwnedCString<'a>, SpirvCrossError> {
if let Some(ptr) = &self.pointer {
// this is either free or very cheap (Rc incr at most)
Ok(MaybeOwnedCString::Borrowed(ptr.clone()))
} else {
let cstring = match self.cow {
Cow::Borrowed(s) => CString::new(s.to_string()),
Cow::Owned(s) => CString::new(s),
};
match cstring {
Ok(cstring) => Ok(MaybeOwnedCString::Owned(cstring)),
Err(e) => {
let string = e.into_vec();
// SAFETY: This string *came* from UTF-8 as its source was the Cow,
// which was preverified UTF-8.
let string = unsafe { String::from_utf8_unchecked(string) };
Err(SpirvCrossError::InvalidString(string))
}
}
}
}
}
#[cfg(test)]
mod test {
use crate::string::CompilerStr;
use std::ffi::{c_char, CStr, CString};
use std::sync::Arc;
struct LifetimeContext(*mut c_char);
impl LifetimeContext {
pub fn new() -> Self {
let cstring = CString::new(String::from("hello")).unwrap().into_raw();
Self(cstring)
}
}
impl Drop for LifetimeContext {
fn drop(&mut self) {
unsafe {
drop(CString::from_raw(self.0));
}
}
}
// struct LifetimeTest<'a>(ContextRoot<'a, LifetimeContext>);
// impl<'a> LifetimeTest<'a> {
// pub fn get(&self) -> ContextStr<'a, LifetimeContext> {
// unsafe { ContextStr::from_ptr(self.0.as_ref().0, self.0.clone()) }
// }
//
// pub fn set(&mut self, cstr: ContextStr<'a, LifetimeContext>) {
// println!("{:p}", cstr.into_cstring_ptr().unwrap().as_ptr())
// }
// }
//
// #[test]
// fn test_string() {
// // use std::borrow::BorrowMut;
// let lc = LifetimeContext::new();
// let ctx = ContextRoot::RefCounted(Arc::new(lc));
//
// let mut lt = LifetimeTest(ctx);
//
// // let mut lt = Rc::new(LifetimeTest(PhantomData));
// let cstr = lt.get();
// lt.set(cstr.clone());
//
// let original_ptr = cstr.clone().into_cstring_ptr().unwrap().as_ptr();
// drop(lt);
//
// assert_eq!("hello", cstr.as_ref());
// println!("{}", cstr);
//
// assert_eq!(original_ptr as usize, cstr.as_ptr() as usize);
// // lt.borrow_mut().set(cstr)
// }
// #[test]
// fn test_string_does_not_allocate() {
// // one past the end
// let mut test = String::with_capacity(6);
// test.push_str("Hello");
//
// let original_ptr = test.as_ptr() as usize;
// let ctxstr = ContextStr::<LifetimeContext>::from(test);
//
// let new_ptr = ctxstr.into_cstring_ptr().unwrap().as_ptr();
// assert_eq!(original_ptr, new_ptr as usize);
// // lt.borrow_mut().set(cstr)
// }
//
// #[test]
// fn test_str_does_allocate() {
// let str = "Hello";
// let original_ptr = str.as_ptr() as usize;
// let ctxstr = ContextStr::<LifetimeContext>::from(str);
//
// let new_ptr = ctxstr.into_cstring_ptr().unwrap().as_ptr();
// assert_ne!(original_ptr, new_ptr as usize);
// // lt.borrow_mut().set(cstr)
// }
//
// #[test]
// fn test_cstr_does_not_allocate() {
// // can't use cstring literals until 1.77
// let str = unsafe { CStr::from_ptr(b"Hello\0".as_ptr().cast()) };
//
// let original_ptr = str.as_ptr() as usize;
// let ctxstr = ContextStr::<LifetimeContext>::from(str);
//
// let new_ptr = ctxstr.into_cstring_ptr().unwrap().as_ptr();
// assert_eq!(original_ptr, new_ptr as usize);
// // lt.borrow_mut().set(cstr)
// }
}